plan/chapter_3_tasks
Raw Download raw file
 1package main
 2
 3import (
 4	"log"
 5	"net/http"
 6)
 7
 8func main() {
 9	// Create an instance of the application struct, containing the application-wide
10	// dependencies and configuration settings.
11	app := &application{
12		logger:      log.New(log.Writer(), "", log.LstdFlags),
13		serviceName: "buylater.email",
14	}
15
16	// Initialize a new servemux (router) - this stores the mapping between
17	// URL patterns and their corresponding handlers.
18	mux := http.NewServeMux()
19
20	// Create a file server which serves files out of the "./ui/static" directory.
21	// Note that the path given to the http.Dir function is relative to the project
22	// directory root.
23	fileServer := http.FileServer(http.Dir("./ui/static/"))
24
25	// Use the mux.Handle() function to register the file server as the handler for
26	// all URL paths that start with "/static/". For matching paths, we strip the
27	// "/static" prefix before the request reaches the file server.
28	mux.Handle("GET /static/", http.StripPrefix("/static", fileServer))
29
30	// Register handlers for buylater.email routes - demonstrating different handler patterns:
31
32	// 1. Method handler converted to http.Handler using http.HandlerFunc
33	mux.Handle("GET /{$}", http.HandlerFunc(app.home))
34
35	// 2. Custom handler type that implements http.Handler interface directly
36	mux.Handle("GET /submit", &TemplateHandler{
37		app:          app,
38		templateName: "submit.tmpl",
39		pageName:     "submit",
40		title:        "Submit",
41	})
42
43	// 3. Method handler with business logic
44	mux.Handle("POST /submit", http.HandlerFunc(app.processSubmit))
45
46	// 4. Simple function handler converted to http.Handler
47	mux.Handle("GET /confirm/{token}", http.HandlerFunc(confirmWithToken))
48
49	// 5. Another custom handler type instance for the about page
50	mux.Handle("GET /about", &TemplateHandler{
51		app:          app,
52		templateName: "about.tmpl",
53		pageName:     "about",
54		title:        "About",
55	})
56
57	// Print a log message to indicate the server is starting.
58	app.logger.Printf("Starting server on http://localhost:4000")
59
60	// Start the web server on port 4000. If ListenAndServe returns an error
61	// we use log.Fatal() to log the error and terminate the program.
62	err := http.ListenAndServe(":4000", mux)
63	log.Fatal(err)
64}