Painless middleware chaining with Alice

The Alice library reduces the complexity of chaining the middleware when the list of middleware is big. It provides us with a clean API to pass the handler to the middleware. In order to install it, use the go get command, like this:

go get github.com/justinas/alice

Now we can import the Alice package in our program and use it straight away. We can modify the sections of the preceding program to bring the same functionality with improved chaining. In the import section, add github.com/justinas/alice, like the following code snippet:

import (
"encoding/json"
"github.com/justinas/alice"
"log"
"net/http"
"strconv"
"time"
)

Now, in the main function, we can modify the handler part like this:

func main() {
mainLogicHandler := http.HandlerFunc(mainLogic)
chain := alice.New(filterContentType, setServerTimeCookie).Then(mainLogicHandler)
http.Handle("/city", chain)
http.ListenAndServe(":8000", nil)
}

The complete code with these added changes is available as a file called multipleMiddlewareWithAlice.go in the chapter 3 folder from the book's GitHub repository. With the knowledge of the preceding concepts, let us build a logging middleware with a library from the Gorilla toolkit called Handlers.

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

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