Skip to content

Instantly share code, notes, and snippets.

@Keithwachira
Created August 1, 2018 05:58
Show Gist options
  • Save Keithwachira/02f25a4d17b9f1f81be3fd855c9ed5df to your computer and use it in GitHub Desktop.
Save Keithwachira/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
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