Middleware Framework For Go net/http.
Fully compatible with http.Handler. To use full featured middleware, you only need to add a no parameter next() call.
go get github.com/withwind8/middlewarepackage main
import (
"log"
"time"
"net/http"
"github.com/withwind8/middleware"
)
func main(){
app := middleware.New()
//a simple log middleware using func
app.UseFunc(func(w http.ResponseWriter, r *http.Request, next func()){
start := time.Now()
next()
log.Printf("%s %v",r.URL.Path,time.Since(start))
})
mux := http.NewServeMux()
mux.HandleFunc("/",func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello World!"))
})
//can using standard http.Handler as middleware
app.UseHandler(mux)
log.Fatal(app.Listen(":8080"))
} Return a middleware container instance
Using a Middleware interface as middleware
type Middleware interface {
ServeHTTP(w http.ResponseWriter, r *http.Request, next func())
}Using a MiddlewareFunc as middleware
type MiddlewareFunc func(w http.ResponseWriter, r *http.Request, next func())Using a http.Handler interface as middleware, next() will be executed automatically at the end
Using a http.HandlerFunc as middleware, next() will be executed automatically at the end
Start the server in with given address.
app.Listen(":8080")is Simply sugar for the following:
http.ListenAndServe(":8080", app)Suppose you have 2 middleware (1 interface 1 func) and 2 handler (1 interface 1 func), and use them in the following order:
app.Use(middleware1)
app.UseHandler(handler1)
app.UseFunc(middleware2)
app.UseHandlerFunc(handler2)Finally, the execution sequence is as follows:
- middleware1_before_next
- handler1
- middleware2_before_next
- handler2
- middleware2_after_next
- middleware1_after_next