Registering server-side routes with Gorilla Mux

We will use the Gorilla Mux router to handle the server-side application routing needs. This router is very flexible since it can not only handle simple routes such as /products but it can also handle routes with embedded variables. Recall that the /product-detail route contains the embedded {productTitle} variable.

We will start by creating a new instance of the Gorilla Mux router and assigning it to the r variable as follows:

  r := mux.NewRouter()

Here's the section of code from the registerRoutes function, defined in the igweb.go source file, where we register routes along with their associated handler functions:

r.Handle("/", handlers.IndexHandler(env)).Methods("GET")
r.Handle("/index", handlers.IndexHandler(env)).Methods("GET")
r.Handle("/products", handlers.ProductsHandler(env)).Methods("GET")
r.Handle("/product-detail/{productTitle}", handlers.ProductDetailHandler(env)).Methods("GET")
r.Handle("/about", handlers.AboutHandler(env)).Methods("GET")
r.Handle("/contact", handlers.ContactHandler(env)).Methods("GET", "POST")

We use the Handle method to associate a route to a given handler function that is responsible for servicing the given route. For example, when the /products route is encountered, it will be handled by the ProductsHandler function defined in the handlers package. The ProductsHandler function will be responsible for fetching the products from the datastore, using the product records to render the products listing page from a template and sending the web page response back to the web client. Similarly, the /product-detail/{productTitle} route will be handled by the ProductDetailHandler function. This handler function will be responsible for fetching the product record for an individual product, using the product record to render the product detail page from a template and sending the web page response back to the web client.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.187.108