Compose middlewares in go-chi?

63 Views Asked by At

I am writing an API using go-chi and my endpoint can be authenticated either via Basic Auth or an API Key. How can I compose two independently functioning middlewares?

Here is what the router looks like:

router := chi.NewRouter()
router.Use(BasicAuthMiddleware)
router.Use(APIKeyMiddleware)

What I really want is to say "If there is a header called X-API-KEY then authenticate the endpoint using APIKeyMiddleware, otherwise use BasicAuthMiddleware."

func CustomMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // What goes here?
    })
}
1

There are 1 best solutions below

0
poundifdef On

Middlewares can be composed by calling ServeHTTP(). For example:

func CustomMiddleware(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        // Look at the values of r to determine which middleware to use
        BasicAuthMiddleware(next).ServeHTTP(w, r)
    })
}