In Go, the Gin framework allows you to easily add middleware to your application. Middleware functions are executed before the main handler and can be used for tasks such as logging, authentication, and modifying requests/responses. This guide provides a simple example of how to implement and use middleware in a Gin application.
To create a middleware in Gin, you define a function that takes a gin.HandlerFunc as a parameter and returns a gin.HandlerFunc. Inside this function, you can perform pre-processing and post-processing of requests.
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"time"
)
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
// Process request
c.Next()
// Calculate duration
duration := time.Since(start)
// Log the request
println("Request processed in", duration)
}
}
func main() {
r := gin.Default()
// Use the Logger middleware
r.Use(Logger())
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "pong"})
})
r.Run(":8080")
}
In this example, we define a Logger
middleware that logs the duration of each request. We then register this middleware with our Gin router using the Use
method, which allows us to apply it globally. When a request hits the /ping
endpoint, the middleware logs the time taken to process that request.
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?