Chapter 3.5.
Isolating the application routes
While we’re refactoring our code there’s one more change worth making.
Our main()
function is beginning to get a bit crowded, so to keep it clear and focused I’d like to move the route declarations for the application into a standalone routes.go
file, like so:
$ cd $HOME/code/snippetbox $ touch cmd/web/routes.go
package main import "net/http" // The routes() method returns a servemux containing our application routes. func (app *application) routes() *http.ServeMux { mux := http.NewServeMux() fileServer := http.FileServer(http.Dir("./ui/static/")) mux.Handle("/static/", http.StripPrefix("/static", fileServer)) mux.HandleFunc("/", app.home) mux.HandleFunc("/snippet/view", app.snippetView) mux.HandleFunc("/snippet/create", app.snippetCreate) return mux }
We can then update the main.go
file to use this instead:
package main ... func main() { addr := flag.String("addr", ":4000", "HTTP network address") flag.Parse() infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime) errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile) app := &application{ errorLog: errorLog, infoLog: infoLog, } srv := &http.Server{ Addr: *addr, ErrorLog: errorLog, // Call the new app.routes() method to get the servemux containing our routes. Handler: app.routes(), } infoLog.Printf("Starting server on %s", *addr) err := srv.ListenAndServe() errorLog.Fatal(err) }
This is quite a bit neater. The routes for our application are now isolated and encapsulated in the app.routes()
method, and the responsibilities of our main()
function are limited to:
- Parsing the runtime configuration settings for the application;
- Establishing the dependencies for the handlers; and
- Running the HTTP server.