gomiddlewarefasthttp

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


Solution

  • 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)
        }
    }