func handler(c *gin.Context) { // retrieve a value stored in the context userID := c.GetInt("user_id") // use the value in request handling fmt.Printf("User ID: %d\n", userID) }
func handler(c *gin.Context) { // set a value in the context c.Set("user_id", 123) }
func authMiddleware() gin.HandlerFunc { return func(c *gin.Context) { // perform authentication userID, err := authenticate(c.Request) if err != nil { c.AbortWithStatus(http.StatusUnauthorized) return } // store the user ID in the context c.Set("user_id", userID) // continue handling the request c.Next() } }In summary, the Context package library in Gin allows for easy management of request-specific values and states, making it a useful tool for middleware and request handling.