在http的handler处理中加上中间件,可以进行过滤、记录日志、统计和统一返回结果
package main import ( "fmt" "net/http" "encoding/json" ) func main() { _ = fmt.Println http.Handle("/test", FormatReturnHandler(HomeHandler)) http.ListenAndServe(":8000", nil) } type normalFunc func(r *http.Request) interface{} type Response struct { Code int `json:"code"` Data interface{} `json:"data"` Msg string `json:"msg"` } func FormatReturnHandler(f normalFunc) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Println(r.URL.Path) ret := Response{} ret.Data = f(r) ret.Code = 0 ret.Msg = "" jsonRet, _ := json.Marshal(&ret) w.Write(jsonRet) }) } func HomeHandler(r *http.Request) interface{} { return r.Host }