Creating HTTP middleware layer
Modern applications with web UI or REST API usually use the middleware mechanism to log the activity, or guard the security of the given interface. In this recipe, the implementation of such a middleware layer will be presented.
How to do it...
- Open the console and create the folder
chapter09/recipe06
. - Navigate to the directory.
- Create the
middleware.go
file with the following content:
package main import ( "io" "net/http" ) func main() { // Secured API mux := http.NewServeMux() mux.HandleFunc("/api/users", Secure(func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, `[{"id":"1","login":"ffghi"}, {"id":"2","login":"ffghj"}]`) })) http.ListenAndServe(":8080", mux) } func Secure(h http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http...