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...