user2515948
user2515948

Reputation:

Fasthttp + fasthttprouter, trying to write middleware

I'm currently trying to write some middleware to work with fasthttp and fasthttprouter. And I'm stuck.

func jwt(h fasthttprouter.Handle) fasthttprouter.Handle {
myfunc := func(ctx *fasthttp.RequestCtx, _ fasthttprouter.Params) {
    fmt.Println(string(ctx.Request.Header.Cookie("Authorization")))
}

return myfunc
}

How do I run the actual handler now? I feel like i'm missing something very simple.

I've read through this blog post: Middleware in Golang. But i'm lost.

Any ideas?

Regards

Upvotes: 6

Views: 9196

Answers (2)

Brrrr
Brrrr

Reputation: 4598

for example, let us create a middleware function that will handle CORS using:

github.com/buaazp/fasthttprouter and github.com/valyala/fasthttp

var (
    corsAllowHeaders     = "authorization"
    corsAllowMethods     = "HEAD,GET,POST,PUT,DELETE,OPTIONS"
    corsAllowOrigin      = "*"
    corsAllowCredentials = "true"
)

func CORS(next fasthttp.RequestHandler) fasthttp.RequestHandler {
    return func(ctx *fasthttp.RequestCtx) {

        ctx.Response.Header.Set("Access-Control-Allow-Credentials", corsAllowCredentials)
        ctx.Response.Header.Set("Access-Control-Allow-Headers", corsAllowHeaders)
        ctx.Response.Header.Set("Access-Control-Allow-Methods", corsAllowMethods)
        ctx.Response.Header.Set("Access-Control-Allow-Origin", corsAllowOrigin)

        next(ctx)
    }
}

Now we chain this middleware function on our Index handler and register it on the router.

func Index(ctx *fasthttp.RequestCtx) {
    fmt.Fprint(ctx, "some-api")
}

func main() {
    router := fasthttprouter.New()
    router.GET("/", Index)

    if err := fasthttp.ListenAndServe(":8181", CORS(router.Handler)); err != nil {
        log.Fatalf("Error in ListenAndServe: %s", err)
    }
}

Upvotes: 20

Denys Adamenko
Denys Adamenko

Reputation: 73

Example of auth middleware for fasthttp & fasthttprouter (new versions)

type Middleware func(h fasthttp.RequestHandler) fasthttp.RequestHandler
type AuthFunc func(ctx *fasthttp.RequestCtx) bool
func NewAuthMiddleware(authFunc AuthFunc) Middleware {
    return func(h fasthttp.RequestHandler) fasthttp.RequestHandler {
        return func(ctx *fasthttp.RequestCtx) {
            result, err: = authFunc(ctx)
            if result {
                h(ctx)
            } else {
                ctx.Response.SetStatusCode(fasthttp.StatusUnauthorized)
            }
        }
    }
}

func AuthCheck(ctx *fasthttp.RequestCtx)(bool, error) {
    return false; // for example ;)
}

// router
authMiddleware: = middleware.NewAuthMiddleware(security.AuthCheck)
    ...
router.GET("/protected", authMiddleware(handlers.ProtectedHandler))

Upvotes: 1

Related Questions