task/1.14
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	// Initialize a new servemux (router) - this stores the mapping between
42	// URL patterns and their corresponding handlers.
43	mux := http.NewServeMux()
44
45	// Create a file server which serves files out of the configured static directory.
46	// Note that the path given to the http.Dir function is relative to the project
47	// directory root.
48	fileServer := http.FileServer(http.Dir(app.config.staticDir))
49
50	// Use the mux.Handle() function to register the file server as the handler for
51	// all URL paths that start with "/static/". For matching paths, we strip the
52	// "/static" prefix before the request reaches the file server.
53	mux.Handle("GET /static/", http.StripPrefix("/static", fileServer))
54
55	// Register handlers for buylater.email routes - demonstrating different handler patterns:
56
57	// 1. Method handler converted to http.Handler using http.HandlerFunc
58	mux.Handle("GET /{$}", http.HandlerFunc(app.home))
59
60	// 2. Custom handler type that implements http.Handler interface directly
61	mux.Handle("GET /submit", &TemplateHandler{
62		app:          app,
63		templateName: "submit.tmpl",
64		pageName:     "submit",
65		title:        "Submit",
66	})
67
68	// 3. Method handler with business logic
69	mux.Handle("POST /submit", http.HandlerFunc(app.processSubmit))
70
71	// 4. Method handler with dependency injection
72	mux.Handle("GET /confirm/{token}", http.HandlerFunc(app.confirmWithToken))
73
74	// 5. Another custom handler type instance for the about page
75	mux.Handle("GET /about", &TemplateHandler{
76		app:          app,
77		templateName: "about.tmpl",
78		pageName:     "about",
79		title:        "About",
80	})
81
82	// Print a log message to indicate the server is starting.
83	app.logger.info.Printf("Starting server on http://localhost:%d in %s mode", app.config.port, app.config.env)
84
85	// Start the web server on the configured port. If ListenAndServe returns an error
86	// we use log.Fatal() to log the error and terminate the program.
87	err := http.ListenAndServe(":"+strconv.Itoa(app.config.port), mux)
88	log.Fatal(err)
89}