e := echo.New() e.Use(func(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { c.Set("userID", 123) return next(c) } }) e.GET("/", func(c echo.Context) error { userID := c.Get("userID").(int) // retrieves the userID value from the context return c.String(http.StatusOK, fmt.Sprintf("User ID: %d", userID)) })
func someMiddleware(next echo.HandlerFunc) echo.HandlerFunc { return func(c echo.Context) error { if c.Path() == "/admin" { if userID := c.Get("userID"); userID == nil { return echo.NewHTTPError(http.StatusUnauthorized, "Unauthorized") } } return next(c) } }This example demonstrates how the `userID` value can be retrieved from the context in a middleware function. Here, the `someMiddleware` function checks if the user is trying to access an admin endpoint and returns a `401 Unauthorized` error if the `userID` value is not present in the context.