A middleware is a function that sits between the server and the client, and it’s executed for each incoming request before it reaches the final handler. A middleware can perform various tasks, such as logging, authentication, validation, and modification of the request or response.
Here’s an example of a simple middleware function in Golang that logs the request method and URL:
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
This middleware function takes an http.Handler as an argument and returns a new http.Handler that wraps it. The returned handler logs the request method and URL before calling the next handler.
You can use this middleware by calling it and passing the next handler as an argument. For example, you can use the middleware in your main function:
func main() {
http.Handle("/", LoggingMiddleware(http.HandlerFunc(index)))
http.ListenAndServe(":8080", nil)
}This way all the requests that hit the ”/” endpoint will pass through the LoggingMiddleware before reaching the index function.
Middlewares can also modify the request or response, for example, you could have a middleware that adds a custom header to the response or that validate the request body. Middlewares are a powerful tool that allows you to handle common functionality in a centralized way, making your code cleaner and more maintainable.
Also, middlewares can be chained together, meaning that you can have multiple middlewares that execute one after the other, this is useful when you want to apply different functionality to the same request, for example, logging, validation, and authentication.