Skip to content

Store processed data from middleware #2197

Answered by aldas
Bean900 asked this question in Q&A
Discussion options

You must be logged in to vote

Context has Set and Get methods that you can use.

func main() {
	e := echo.New()

	e.Use(middleware.Logger())
	e.Use(middleware.Recover())
	e.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
		return func(c echo.Context) error {
			c.Set("claim", "claim") // add value to context store
			return next(c)
		}
	})

	e.GET("/", func(c echo.Context) error {
		claim, ok := c.Get("claim").(string) // extract value from context and cast it into string
		if !ok {
			return c.String(http.StatusInternalServerError, "missing claim or cast failure")
		}
		return c.String(http.StatusOK, claim)
	})

	if err := e.Start(":8080"); err != http.ErrServerClosed {
		log.Fatal(err)
	}
}

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@Bean900
Comment options

Answer selected by Bean900
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants