Skip to content
This repository has been archived by the owner on Sep 21, 2022. It is now read-only.

Middlewares

Volker Wiegand edited this page Jun 23, 2017 · 5 revisions

What are middlewares?

Middlewares are functions that run before HTTP request hits the controller method (controller action). If you are familiar with PHP frameworks, middlewares can be compared to the beforeAction() methods.

Why would I use middlewares?

So that you don't need to repeat yourself. Why would you check if user is authenticated in each controller action? Let's do that in a middleware and then handle this information, for example reditect user to sign in page.

There are more uses, for example:

  • counting how many users are currently browsing the website,
  • measuring request time,
  • restrict access to some user groups

And whatever comes to your mind.

Okay, how to actually use the middlewares?

It's simple. In utron you can define middlewares of two types, that is:

func (http.Handler) http.Handler

and

func (*utron.Context) error

This example middleware checks if user is currently authenticated and looks like this:

func checkSession(c *utron.Context) error {
	session, _ := SessionStorage.Get(c.Request(), "golang-session")
	// this conditional is required as we don't want to have nil in context data
	if session.Values["logged_in"] != nil {
		c.SetData("logged_in", true)
		c.SetData("user_id", session.Values["user_id"])
	} else {
		c.SetData("logged_in", false)
		c.SetData("user_id", -1)
	}
	session.Save(c.Request(), c.Response())

        // no errors, so we return nil
	return nil
}

Note: I am using gorilla/sessions here to handle sessions.

Now it's time to tell utron that we want the middleware to be executed

This means that we have to register the middleware. This is done in controller init function. You just have to pass the middleware name (function name) to utron.AddController. You can register as many middlewares as you want.

func init() {
	utron.AddController(NewTODO(), checkSession, sampleMiddleware1, sampleMiddleware2) // and so on
}

Utron uses Alice to chain middlewares.

That's it!

Now your middlewares will be executed on each http request.