Skip to content

Instantly share code, notes, and snippets.

@nanoninja
Last active July 10, 2016 09:55
Show Gist options
  • Save nanoninja/17a2aa83d34c7eed0c3a to your computer and use it in GitHub Desktop.
Save nanoninja/17a2aa83d34c7eed0c3a to your computer and use it in GitHub Desktop.
Go Middleware
// Copyright 2016 Vincent Letourneau.
package main
import (
"fmt"
"net/http"
)
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Auth Middleware")
next.ServeHTTP(w, r)
})
}
func TestMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Test Middleware")
next.ServeHTTP(w, r)
})
}
func SayHelloMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Println("Hello Middleware")
next.ServeHTTP(w, r)
})
}
func LastHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("Last Handler")
}
func main() {
fmt.Println("Server is running...")
handler := Use(AuthMiddleware, TestMiddleware, SayHelloMiddleware).HandlerFunc(LastHandler)
http.Handle("/", handler)
http.ListenAndServe(":3000", nil)
}
// Copyright 2016 Vincent Letourneau.
package main
import "net/http"
type Middleware func(http.Handler) http.Handler
func Use(mw ...Middleware) Middleware {
return Middleware(func(next http.Handler) http.Handler {
if next == nil {
next = http.NewServeMux()
}
for i := len(mw) - 1; i >= 0; i-- {
next = mw[i](next)
}
return next
})
}
func (mw Middleware) Use(middleware ...Middleware) Middleware {
return Middleware(func(next http.Handler) http.Handler {
return Use(middleware...).Handler(mw(next))
})
}
func (mw Middleware) Handler(next http.Handler) http.Handler {
return mw(next)
}
func (mw Middleware) HandlerFunc(next http.HandlerFunc) http.Handler {
return mw.Handler(next)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment