中间件是把http.Handler包装后做请求的一些预处理或后处理。
#例子:
package main
import (
"fmt"
"log"
"net/http"
)
func test(w http.ResponseWriter, r *http.Request){
fmt.Fprintln(w, "test")
}
// 封装中间件
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println(r.URL.Path)
next.ServeHTTP(w, r)
})
}
func main() {
http.Handle("/test", middleware(http.HandlerFunc(test)))
http.ListenAndServe(":8080", nil)
}