Skip to content

Best way to pass parameter from middleware to handler #2707

Answered by chr1shung
chr1shung asked this question in Q&A
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