Golang logging http responses (in addition to requests)

前端 未结 3 1552
悲&欢浪女
悲&欢浪女 2020-12-19 05:29

I am using Go and the Gorilla web toolkit\'s mux and handler packages to build a complex application, part of which requires a http server. Gorilla\'s mux and handler packa

3条回答
  •  天涯浪人
    2020-12-19 06:18

    The accepted answer by Eric Broda won't help much if you want to actually send your response to the client. I've made a modification to that code that will actually work:

    func logHandler(fn http.HandlerFunc) http.HandlerFunc {
        return func(w http.ResponseWriter, r *http.Request) {
            x, err := httputil.DumpRequest(r, true)
            if err != nil {
                http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
                return
            }
            log.Println(fmt.Sprintf("%q", x))
            rec := httptest.NewRecorder()
            fn(rec, r)
            log.Println(fmt.Sprintf("%q", rec.Body))        
    
            // this copies the recorded response to the response writer
            for k, v := range rec.HeaderMap {
                w.Header()[k] = v
            }
            w.WriteHeader(rec.Code)
            rec.Body.WriteTo(w)
        }
    }
    

提交回复
热议问题