O'Reilly logo

Go Standard Library Cookbook by Radomir Sohlich

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How it works...

The implementation of middleware in the preceding example leverages the functions as first-class citizens feature of Golang. The original HandlerFunc is wrapped into a HandlerFunc which checks the X-Auth header. The Secure function is then used to secure the HandlerFunc, used in the HandleFunc methods of ServeMux.

Note that this is just a simple example, but this way you can implement more sophisticated solutions. For example, the user identity could be extracted from the Header token and subsequently, the new type of handler could be defined as type AuthHandler func(u *User,w http.ResponseWriter, r *http.Request). The function WithUser then creates the HandlerFunc for the ServeMux.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required