func main() { r := gin.Default() r.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.JSON(http.StatusOK, gin.H{"name": name}) }) fmt.Println("Server started at :8080") r.Run(":8080") }
func AuthMiddleware() gin.HandlerFunc { return func(c *gin.Context) { if c.Query("password") == "secret" { c.Set("authenticated", true) } else { c.AbortWithStatus(http.StatusUnauthorized) } } } func main() { r := gin.Default() r.Use(AuthMiddleware()) r.GET("/private", func(c *gin.Context) { if v, ok := c.Get("authenticated"); ok { c.JSON(http.StatusOK, gin.H{"authenticated": v}) } else { c.JSON(http.StatusUnauthorized, gin.H{"message": "authentication failed"}) } }) fmt.Println("Server started at :8080") r.Run(":8080") }In this example, we define a middleware that checks if the query parameter "password" is equal to "secret" and sets a value to the context object. We use this middleware to protect a private route that can only be accessed by authorized users. If the authorization check passes, we return a JSON response with the authenticated value. If it fails, we return a 401 status code with an error message. Overall, the "Context" package in the "github.com/gin-gonic/gin" library allows developers to handle communication between different modules in a request-response cycle, such as middleware, handlers, and templates.