-
Hi, I'm trying to validate an API key, which encodes a username, and then use that username in a subsequent handler. But then how to pass that user to the following handler? thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You can use const MyValueContextKey = "my-context-value"
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 {
value := c.QueryParam("value")
if value != "" {
c.Set(MyValueContextKey, value) // store in context
}
return next(c)
}
})
e.GET("/", func(c echo.Context) error {
value, ok := c.Get(MyValueContextKey).(string) // get from context
if !ok {
value = "no value in context"
}
return c.String(http.StatusOK, value)
})
if err := e.Start(":8080"); err != http.ErrServerClosed {
log.Fatal(err)
}
} Example: x@x:~/code$ curl -v http://localhost:8080/?value=test
* Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /?value=test HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.74.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=UTF-8
< Date: Mon, 07 Mar 2022 17:52:30 GMT
< Content-Length: 4
<
* Connection #0 to host localhost left intact
test x@x:~/code$ curl -v http://localhost:8080/?
* Trying 127.0.0.1:8080...
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /? HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.74.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< Content-Type: text/plain; charset=UTF-8
< Date: Mon, 07 Mar 2022 17:52:17 GMT
< Content-Length: 19
<
* Connection #0 to host localhost left intact
no value in context and for KeyAuth it would look something like that e.Use(middleware.KeyAuth(func(auth string, c echo.Context) (bool, error) {
if auth == "mysecret" {
user := auth // FIXME: encode auth to user
c.Set(MyValueContextKey, user)
return true, nil
}
return false, nil
})) |
Beta Was this translation helpful? Give feedback.
You can use
echo.Context.Set
andecho.Context.Get
to store value in middleware into context and get that value from context in downstream middlewares or handler