So in this article lets discuss how a request is processed in a Go application. So we gonna have an instance of a request handler somewhere in the application. When a request comes in it is going to get routed to the request handler, the request handler is going to process that request and generate a response back.
Well when we want to you use middleware, we actually going to shove the request the request handler over and inject a middleware right here in the request processing pipeline.
So now when a request comes in it is actually going to come into the middleware first. The middleware forward it to the request handler, the request handler is going to generate a response and the response is going throught the middleware and the response is goint to be send to the requestor. Now in this case the middleware has a quite lot of power, since it can manipulate the request as its coming in, and also manipulate before it goes back to the requestor.
Now lets illustrate a dummy. To use a middleware you should replace the nil parameter in the well known
http.ListenAndServe(":8000", nil)
function with a constructor function.
An example of middleware
type MyMiddleware struct {
Next http.Handler
}
func (m MyMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
/* do things before the next handler */
m.Next.ServeHTTP(w,r)
}
and use
http.ListenAndServe(":8000", new MyMiddleware)
The good thing is that middlewares are chainable, so when you call the Next method, you can call your next middleware and so on. This way you can split your code into small piece of logics.
Common usecases for middlewares:
- Logging - for analytic information
- Security - for filter to allow or deny different parts of the application
- Request timeouts
Did you find this article valuable?
Support Renátó Bogár by becoming a sponsor. Any amount is appreciated!