CodeX
Published in

CodeX

Creating Middleware with httprouter

Photo by Jametlene Reskp on Unsplash

Why httprouter

There are many Multiplexers available, with popular ones being Gorilla Mux, httprouter, and Bone. For this article, I will explore httprouter, one I often use because I like how simple and efficient it is. But also because there is a version available for both net/http and fasthttp. I use both of these HTTP packages throughout my various projects. And having one HTTP Multiplexer to use regardless of which I'm using helps keep things simple.

Getting Started with httprouter

Before jumping into creating an HTTP middleware function, we should first start with the basics of using httprouter. We can look at the most basic HTTP service that prints “Hello World” to kick us off.

Creating our HTTP Middleware

For this article, we will create a basic logger middleware. This middleware aims to create a consistent log of HTTP requests regardless of what HTTP handler executes. That means before our handler() function executes, we want our middleware to run first.

Registering non-Custom Handlers with the HTTP middleware

A common practice for libraries such as PProf is to provide HTTP handlers as part of the package interface. The net/http/pprof package has several functions that adhere to the standard net/http method signature. Functions such as Index, which handles the /debug/pprof/ end-point, and Profile, which serves the /debug/pprof/profile CPU profiling end-point.

Summary

With the above, we have a simple hello world application that shows how easy it is to create HTTP Middleware functions with httprouter. We can also see how it is possible to use this middleware even with packages like PProf, where the HTTP handlers use a different signature.

--

--

Everything connected with Tech & Code. Follow to join our 1M+ monthly readers

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store