目前能做到打印request以及消耗时间,但是无法打印response数据,需要一个解决方法获取reponse里的statusCode和body。
func logReqAndRes(start time.Time, requestData []byte, w http.ResponseWriter, r *http.Request) {
t := time.Now()
elapsed := t.Sub(start)
requestDataArray := strings.Split(string(requestData),"\r\n")
body, _ := url.QueryUnescape(requestDataArray[len(requestDataArray)-1])
log.WithFields(log.Fields{
"request.Url":r.URL.Path,
"request.Query":r.URL.RawQuery,
"request.Host":r.Host,
"request.Method":r.Method,
"request.Header":r.Header,
"request.Body": body,
"duration(ms)": float64(elapsed)/1000000.0,
}).Info("request")
// 但是无法通过w获取response的数据
fmt.Println(w)//这个打印的数据并不是我需要的
}
func Interceptor(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
dumpRequest, _ := httputil.DumpRequest(r, true)
h.ServeHTTP(w, r)
logReqAndRes(start,dumpRequest,w,r)
})
}
有疑问加站长微信联系(非本文作者)