Using Middleware In Go The Right Way

Using Middleware In Go The Right Way

Middlewares are an essential part of each and every api or web application.Golang makes this an easy and painless process to integrate a middleware in your application.You can opt for third party libraries such as negroni or Alice for writing your middleware but why add extra dependency to your application while middleware are so easy to write with the standard library?In this tutorial we are going to write a Middleware In Go for a simple api that we will write.You can get the full code from here.

Making a simple go api

We are going to use the api we wrote in the last tutorial.If you have not yet looked at it yet here it is how to deploy golang to prodution.For the sake of conveniency am going to repeat the same api here.

If you already have an existing golang api,feel free to skip to the making the middleware section.

This will be our project structure.

The handlers.go- has all the handlers(controllers) we want to hook to our routes

The models.go-This contains all our model definition which in this case is  our job model.

The Main.go – This is our entry point where we shall serve our application from.

middleware.go-We are going to define all our middleware in this  file.

Defining our model

We are going to have one model for the sake of simplicity.If your application has many models you should define them here.In practice if you have a big and complex project you define models in related packages .

 

Simple handler to serve our jobs

Now that we have our model ready it time to write a simple handler to serve our jobs.Every request we send  requesting for jobs will be servered by this method.We will later hook it with a route in the main package.

The handler will return a json response which we can consume.

Serving our jobs

In this tutorial i am going to use the bone  Multiplexer  to handle my routing but feel free to use any router available.

Now copy the following code in your main.go.

Our api is now complete.You can test it by running.

Making A Middleware in go

Lets define middleware that logs the time the request was sent.I am going to keep it  as simple as possible.

Lets start by writing the code and i will later explain what is happening.

Copy this in the middleware.go file

The  reason we have defined our middleware function that takes in a http.Handler and return a http.Handler is to allow us to chain multiple middlewares.

The LogTime middleware logs the time a request was sent to our server.If for example you wanted to check for a user token in an api protected with jwt you would use the same format.

Using our middleware

The best way to use middlewares i golang is writing a simple function that will help to adapt our handler with all the middleware it requires.

The function should take in our handler(that is the GetJob) and a slice of all middleware we want to use with GetJobs.

Copy this code to in the middleware.go.

What happens here is that we pass a handler e.g(The GetJobs)and a slice of all the middlewares we want that handler to use.Then the adapted  handler is returned.

Modify the main.go to look like below .So that our (GetJobs handler can use our middleware).

Every time you send a request to  the (api/jobs) it should log the time the request  was sent.

As you may have noticed sometimes an endpoint may need to use more than one middleware.With the approach we have taken this will be very easier as our  adapt function accepts a slice  of middlewares.Lets try this with two middlewares.

Chaining Multiple Middlewares in go

Imagine you want to print some text every time you receive a request .Lets say something like.”I like chocolate”.You can make a middleware that does this.Note:I am using fairly simple middlewares to make it as simple as possible to understand.For a real world project your will be making middlewares to do work like checking for a user jwt token.However the implementation is the same.

Copy the code below in your middleware.go.

Finally update the main.go to let our  GetJobs handler use both middlewares.

At this point if you try visiting this endpoint you will realize our endpoint is now using both middlewares.

It print both the current time(middleware.Logtime) and ‘i like chocolate’ (second middleware).

golang middlewares

Using this approach you can chain as many middleware as you wish.

Conclusion

In this tutorial we have seen how easy it is to write and use middlewares in golang.You can also read some of our previous tutorials How to deploy golang apps or enroll for our free classes at codesahara.

You can get the whole code for this tutorial on github.

Happy coding.

 

 

 

Leave a Comment