-
Notifications
You must be signed in to change notification settings - Fork 150
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.
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.
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.
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.
Now your middlewares will be executed on each http request.