I'm wondering if there's any better way/convention to handle this scenario ?
\nthanks for the help !
I'm using something like this and works pretty well:
\npackage main\n\nimport (\n\t\"github.com/labstack/echo/v4\"\n\t\"net/http\"\n)\n\ntype Request struct {\n\tID int `json:\"id\"`\n\tPayload string `json:\"payload\"`\n}\n\nfunc main() {\n\te := echo.New()\n\te.POST(\"/api\", Authz(Handler))\n\te.Logger.Fatal(e.Start(\":1323\"))\n}\n\nfunc Authz(next OurHandler[Request]) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tvar req Request\n\t\terr := c.Bind(&req)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusBadRequest, err.Error())\n\t\t}\n\t\t// perform the authorization\n\n\t\treturn next(c, req)\n\t}\n}\n\ntype OurHandler[In any] func(echo.Context, In) error\n\nfunc Handler(c echo.Context, req Request) error {\n\t// perform the actual request\n\treturn nil\n}-
|
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.
-
|
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: