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?
})
}
Middlewares can be composed by calling
ServeHTTP(). For example: