-
I saw this comment #782 (comment) said 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 echo.HandlerFunc) 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
c.Set("request", req)
return next(c)
}
}
func Handler(c echo.Context) error {
req := c.Get("request").(Request)
// perform the actual request
return nil
} I'm wondering if there's any better way/convention to handle this scenario ? |
Beta Was this translation helpful? Give feedback.
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'm using something like this and works pretty well: