Skip to content
\n

I'm wondering if there's any better way/convention to handle this scenario ?
\nthanks for the help !

","upvoteCount":1,"answerCount":2,"acceptedAnswer":{"@type":"Answer","text":"

I'm using something like this and works pretty well:

\n
package 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}
","upvoteCount":0,"url":"https://github.com/labstack/echo/discussions/2707#discussioncomment-11343658"}}}
Discussion options

You must be logged in to vote

I'm using something like this and works pretty well:

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[Request]) 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[In any] func(echo.Context, In) error

func Handler(c echo.Context, req Request) error {
	// pe…

Replies: 2 comments 2 replies

Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
2 replies
@aldas
Comment options

@chr1shung
Comment options

Answer selected by chr1shung
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