func handler(c *gin.Context) { c.Set("userID", "1234") userID := c.GetString("userID") c.String(http.StatusOK, "User ID: %s", userID) }
func middleware() gin.HandlerFunc { return func(c *gin.Context) { c.Set("foo", "bar") c.Next() } } func handler(c *gin.Context) { fooValue := c.MustGet("foo").(string) c.String(http.StatusOK, "Value of foo: %s", fooValue) } func main() { r := gin.Default() r.Use(middleware()) r.GET("/test", handler) r.Run(":8080") }In this example, we create a middleware function that sets a key-value pair of "foo" and "bar" on the context. This middleware is then applied to all routes using the `Use` method. In the handler function, we retrieve the "foo" value using the `MustGet` method and print it to the response. Overall, the gin-gonic/gin package provides a simple and efficient way to manage Context Data when building Go web applications.