在http的handler处理中加上中间件,可以进行过滤、记录日志、统计和统一返回结果
1 package main 2 ?3 import ( 4 ????"fmt" 5 ????"net/http" 6 ????"encoding/json" 7 ) 8 ?9 func main() {10 ????_ = fmt.Println11 ????http.Handle("/test", FormatReturnHandler(HomeHandler))12 ????http.ListenAndServe(":8000", nil)13 }14 15 type normalFunc func(r *http.Request) interface{}16 17 type Response struct {18 ????Code int ????????`json:"code"`19 ????Data interface{} `json:"data"`20 ????Msg ?string ????????`json:"msg"`21 }22 23 func FormatReturnHandler(f normalFunc) http.Handler {24 ????return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {25 ????????fmt.Println(r.URL.Path)26 27 ????????ret := Response{}28 ????????ret.Data = f(r)29 ????????ret.Code = 030 ????????ret.Msg = ""31 ????????jsonRet, _ := json.Marshal(&ret)32 33 ????????w.Write(jsonRet)34 ????})35 }36 37 func HomeHandler(r *http.Request) interface{} {38 ????return r.Host39 }
Go http handler 中间件
原文地址:https://www.cnblogs.com/linguoguo/p/10553716.html