Middleware 中间件 === 比如访问这个url需要用户登陆就可以在用户访问的前一层作判断用户登陆 ~~~ // 自定义原生中间件 package main import ( "github.com/julienschmidt/httprouter" "net/http" "strings" ) func MiddleAuth(router httprouter.Handle) httprouter.Handle { return httprouter.Handle( func(writer http.ResponseWriter, request *http.Request, params httprouter.Params) { token := request.Header.Get("token") if strings.EqualFold(token,"tokenId") { router(writer,request,params) return } writer.WriteHeader(401) writer.Write([]byte("401")) }) } func RegisRouter() *httprouter.Router{ router := httprouter.New() router.GET("/home",MiddleAuth(home)) return router } func home(w http.ResponseWriter,r *http.Request,p httprouter.Params) { } func main() { router := RegisRouter() http.ListenAndServe(":8085",router) } ~~~ 也可以获取验证通过的value ~~~ import ( "fmt" "github.com/julienschmidt/httprouter" "net/http" ) func RegisterRouter() *httprouter.Router { router := httprouter.New() router.GET("/chat/:id",middlewareAuth(chat)) return router } func main() { router := RegisterRouter() fmt.Println("server run http://127.0.0.1:9001 ...") if err := http.ListenAndServe(":9001", router);err != nil { panic(err.Error()) } } func middlewareAuth(route httprouter.Handle) httprouter.Handle { return httprouter.Handle(func(w http.ResponseWriter,r *http.Request,p httprouter.Params) { token := r.Header.Get("token") if token == "token" { r.ParseForm() r.PostForm.Set("name","dollarkiller") // 验证通过设置他 route(w,r,p) return } w.WriteHeader(401) w.Write([]byte("401")) }) } func chat(w http.ResponseWriter,r *http.Request,p httprouter.Params) { r.ParseForm() name := r.PostForm.Get("name") // 获取它 fmt.Println(name) id := p.ByName("id") w.Write([]byte(id)) } ~~~