请注意,MyResponseWriter.Write()只将数据写入缓冲区。您也可以选择立即检查它(在Write()方法中)并立即将数据写入包装/嵌入ResponseWriter. 你甚至可以修改数据。你有完全的控制权。: W* u6 X2 x# Q o$ d
但必须再次小心,因为后续处理程序也可能发送与响应数据相关的 HTTP 响应标头-如长度或验证-如果您更改响应数据,这些标头也可能无效。 + R2 r) t& z( M* c完整示例把这些部分放在一起是一个完整的工作示例: 9 }1 F0 t. f& S4 W! ?" j* q[code]func loginmw(handler http.Handler) http.Handler return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) body,err := ioutil.ReadAll(r.Body) if err != nil log.Printf("Error reading body: %v",err) http.Error(w,"can't read body",http.StatusBadRequest) return Work / inspect body. You may even modify it! And now set a new body,which will simulate the same data we read: r.Body = ioutil.NopCloser(bytes.NewBuffer(body)) Create a response wrapper: mrw := &MyResponseWriter ResponseWriter: w, buf: &bytes.Buffer{}, } Call next handler,passing the response wrapper: handler.ServeHTTP(mrw,r) Now inspect response,and finally send it out: (You can also modify it before sending it out!) if _,err := io.Copy(w,mrw.buf); err != nil log.Printf("Failed to send out response: %v",err) }code]