Chapter 9.1.
The http.Server struct
So far in this book we’ve been using the http.ListenAndServe()
shortcut function to start our server.
Although http.ListenAndServe()
is very useful in short examples and tutorials, in real-world applications it’s more common to manually create and use a http.Server
struct instead. Doing this opens up the opportunity to customize the behavior of your server, which is exactly that we’ll be doing in this section of the book.
So in preparation for that, let’s quickly update our main.go
file to stop using the http.ListenAndServe()
shortcut, and manually create and use a http.Server
struct instead.
package main ... func main() { addr := flag.String("addr", ":4000", "HTTP network address") dsn := flag.String("dsn", "web:pass@/snippetbox?parseTime=true", "MySQL data source name") flag.Parse() logger := slog.New(slog.NewTextHandler(os.Stdout, nil)) db, err := openDB(*dsn) if err != nil { logger.Error(err.Error()) os.Exit(1) } defer db.Close() templateCache, err := newTemplateCache() if err != nil { logger.Error(err.Error()) os.Exit(1) } formDecoder := form.NewDecoder() sessionManager := scs.New() sessionManager.Store = mysqlstore.New(db) sessionManager.Lifetime = 12 * time.Hour app := &application{ logger: logger, snippets: &models.SnippetModel{DB: db}, templateCache: templateCache, formDecoder: formDecoder, sessionManager: sessionManager, } // Initialize a new http.Server struct. We set the Addr and Handler fields so // that the server uses the same network address and routes as before. srv := &http.Server{ Addr: *addr, Handler: app.routes(), } logger.Info("starting server", "addr", srv.Addr) // Call the ListenAndServe() method on our new http.Server struct to start // the server. err = srv.ListenAndServe() logger.Error(err.Error()) os.Exit(1) } ...
This is a small change which doesn’t affect our application behavior (yet!), but it sets us up nicely for the work to come.