Created
August 1, 2018 05:58
-
-
Save yurisasuke/02f25a4d17b9f1f81be3fd855c9ed5df to your computer and use it in GitHub Desktop.
This is a simple file showing how to write middleware in golang.It also provides an easy way of chaining middlewares
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package middleware | |
import ( | |
"net/http" | |
"strings" | |
) | |
type Middleware func( http.Handler) http.Handler | |
//a function that returns a middleware type | |
func ValidateUserToken() Middleware { | |
return func(h http.Handler) http.Handler { | |
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
///your middleware logic goes here e.g user validation | |
h.ServeHTTP(w, r) | |
}) | |
} | |
} | |
func Adapt(h http.Handler, adapters ...Middleware) http.Handler { | |
///This functions allows you to chain multiple middlewares | |
///You pass a list of middleware and a handler and it returns a handler | |
for _, adapter := range adapters { | |
h = adapter(h) | |
} | |
return h | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment