The following table lists the HTTP request types and endpoints that our frontend service needs to handle in order to implement all the features we described previously:
Request Type | Path | Description |
GET | / | Displays the index page |
GET | /search?q=TERM | Displays the first page of results for TERM |
GET | /search?q=TERM&offset=X | Displays the results for TERM, starting from a particular offset |
GET | /submit/site | Displays the site submission form |
POST | /submit/site | Handles a site submission |
ANY | Any other path | Displays a 404 page |
To make our life easier, we will be using gorilla/mux as our preferred router. Creating the router and registering the endpoint handlers is as simple as using the following code:
svc := &Service{ router: mux.NewRouter(), cfg: cfg, } svc.router.HandleFunc(indexEndpoint, svc.renderIndexPage).Methods("GET") svc.router.HandleFunc(searchEndpoint, svc.renderSearchResults).Methods("GET") svc.router.HandleFunc(submitLinkEndpoint, svc.submitLink).Methods("GET", "POST") svc.router.NotFoundHandler = http.HandlerFunc(svc.render404Page)
To make the frontend service easier to test, the Service type stores a reference to the router. This way, we can use the httptest package primitives to perform HTTP requests directly at the mux without having to spin up any servers.