visit our site
golang, middleware, negroni

Using Negroni middleware in Golang for specific routes with httprouter

In Blog, Golang

by Laurentiu Craciun on September 7, 2017

In the last days I’ve played a little bit with negroni middleware and httprouter router. I found that the documentation about how can we use negroni middlewares for specific routes with httprouter is pretty poor. So I decided to write this article to share with you what I’ve found.

Negroni is an idiomatic approach to web middleware in Golang which will help you build and stack middleware very easily. It comes with some default middlewares like:

  • negroni.Recovery – Panic Recovery Middleware.
  • negroni.Logger – Request/Response Logger Middleware.
  • negroni.Static – Static File serving under the “public” directory.

But it also letting you create your own middlewares very easily:

Negroni is BYOR (Bring your own Router) so we can use it with httprouter.

Httprouter is a Golang lightweight and high performance HTTP request router which is fast and has low memory consumption. TLDR: it is one of the fastest routers.

Here you have an example on how a simple route can be added when using httprouter:

Where loginHandler will look like:

Now lets suppose you want to access GET profile endpoint but you need to be authenticated.
We will start by creating an authentication middleware:

Then we will create a handler which will return profile information after the authentication will be done. This handler will be sent to the auth middleware as a callback using “next” parameter:

Now let’s send everything to the router:

That was simple, but now if we have a route which contains parameters inside it (like /hello/:name) we cannot access it from our handler function. To solve that, I’ve written the following functions which will help us call the handler with the parameters:

And will be used like this:

 

The full working example can be found here.

Leave a Reply

Your email address will not be published. Required fields are marked *

+1
Share7
Tweet
Share4
Stumble
Pin