task/1.15
Raw Download raw file
 1package main
 2
 3import (
 4	"flag"
 5	"log"
 6	"net/http"
 7	"os"
 8	"strconv"
 9)
10
11func main() {
12	// Declare an instance of the config struct to hold configuration settings
13	var cfg config
14
15	// Parse command-line flags with sensible defaults
16	flag.IntVar(&cfg.port, "port", 4000, "HTTP server port")
17	flag.StringVar(&cfg.env, "env", "development", "Environment (development|staging|production)")
18	flag.StringVar(&cfg.staticDir, "static-dir", "./ui/static", "Path to static assets")
19	flag.StringVar(&cfg.htmlDir, "html-dir", "./ui/html", "Path to HTML templates")
20	flag.Parse()
21
22	// Check for environment variable overrides
23	if envPort := os.Getenv("PORT"); envPort != "" {
24		if port, err := strconv.Atoi(envPort); err == nil {
25			cfg.port = port
26		}
27	}
28	if envEnv := os.Getenv("ENV"); envEnv != "" {
29		cfg.env = envEnv
30	}
31	if envStaticDir := os.Getenv("STATIC_DIR"); envStaticDir != "" {
32		cfg.staticDir = envStaticDir
33	}
34	if envHtmlDir := os.Getenv("HTML_DIR"); envHtmlDir != "" {
35		cfg.htmlDir = envHtmlDir
36	}
37
38	// Initialize application dependencies
39	app := initializeApplication(cfg)
40
41	// Configure application routes
42	mux := app.routes()
43
44	// Print a log message to indicate the server is starting.
45	app.logger.info.Printf("Starting server on http://localhost:%d in %s mode", app.config.port, app.config.env)
46
47	// Start the web server on the configured port. If ListenAndServe returns an error
48	// we use log.Fatal() to log the error and terminate the program.
49	err := http.ListenAndServe(":"+strconv.Itoa(app.config.port), mux)
50	log.Fatal(err)
51}