DEV Community

Gabe
Gabe

Posted on

4 2

Golang Fasthttp Middleware

I am using FastHttp to implemente Http in go. Most people are using Gorilla Mux, but I decided to try a different http implementation.

There are scenarios where a request should chained, I mean, we must execute previous actions before handling the request resolver itself. The most common case is evaluating Authorization before executing the business.

Having said that, lets imagine a scenario where we must have an endpoint that must be protected by an Auth middleware, check for token and if its valid you can execute the business otherwise you get a 401 http status.

First set up the router

router := fasthttprouter.New()
router.GET("/", GetProducts)
fasthttp.ListenAndServe(":5002", router.Handler)
Enter fullscreen mode Exit fullscreen mode

The GetProducts is a function that simply respond with a product object. For example:

func GetProducts(ctx *fasthttp.RequestCtx) {

    product := &productModel.Product{}
    product.Id = "123890"
    product.Name = "Shoes"
    product.Price = 100.30

    json.NewEncoder(ctx).Encode(response)
}
Enter fullscreen mode Exit fullscreen mode

Now we are going to create our Auth Middleware

func Auth(requestHandler fasthttp.RequestHandler) fasthttp.RequestHandler {
    return func(ctx *fasthttp.RequestCtx) {
        token := string(ctx.Request.Header.Peek("Authorization"))

        if token == "" {
            return 
        } else {
               requestHandler(ctx)
                }
    }
}
Enter fullscreen mode Exit fullscreen mode

And now... we are going to wrap the GetProducts on router.Get method wit

router.GET("/", Auth(GetProducts))
Enter fullscreen mode Exit fullscreen mode

So, if you get until here you may want to understand how it works.

-- add

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay