Replies: 2 comments 2 replies
-
When it comes to binding request body I think handlers are more appropriate place for it. but if all your handlers require same middleware and you want to use like you do (when adding the route) - you could just design different handler signature. so instead of package main
import (
"github.com/labstack/echo/v4"
"net/http"
)
type Request struct {
ID int `json:"id"`
Payload string `json:"payload"`
}
func main() {
e := echo.New()
e.POST("/api", Authz(Handler))
e.Logger.Fatal(e.Start(":1323"))
}
func Authz(next OurHandler) echo.HandlerFunc {
return func(c echo.Context) error {
var req Request
err := c.Bind(&req)
if err != nil {
return echo.NewHTTPError(http.StatusBadRequest, err.Error())
}
// perform the authorization
return next(c, req)
}
}
type OurHandler func(c echo.Context, req Request) error
func Handler(c echo.Context, req Request) error {
// perform the actual request
return nil
} |
Beta Was this translation helpful? Give feedback.
-
@aldas thanks that's brilliant. |
Beta Was this translation helpful? Give feedback.
-
I saw this comment #782 (comment) said
Bind
cannot be read again.I have a use case which the middleware will read the request body and do the authorization, after that the api handler will proceed to do the following work.
Below is an example how I'm doing this currently using
echo.Context
:I'm wondering if there's any better way/convention to handle this scenario ?
thanks for the help !
Beta Was this translation helpful? Give feedback.
All reactions