dongxueji2838 2016-07-18 18:42
浏览 259
已采纳

Golang记录http响应(除了请求)

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 packages work wonderfully and I am able to successfully get the http server up and running and it has been quite simple to log requests.

However, I am unable to determine how I may log responses. Ideally, I would like a mechanism, similar to Gorilla's LoggingHandler, that "wraps" the logging mechanism easily.

Is there a Golang package that does easily wraps / logs responses? Is there a way to use Go or Gorilla's capabilities in this fashion that I have not considered?

  • 写回答

3条回答 默认 最新

  • dongzhun4898 2016-07-19 21:51
    关注

    Thanks for the great suggestions. I tried a few of the suggestions and landed on a rather simple solution that uses a minimalist wrapper. Here is the solution that worked for me (feel free to offer comments, or better yet, other solutions):

    import (
        "fmt"
        "log"
        "net/http"
        "net/http/httptest"
        "net/http/httputil"
        "github.com/gorilla/mux"
    )
    :
    
    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))            
        }
    }
    
    func MessageHandler(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintln(w, "A message was received")
    }
    

    And the following code will use the aforementioned handler:

    :
    router := mux.NewRouter()
    router.HandleFunc("/", logHandler(MessageHandler))
    :
    

    Output from the above code will be something along the lines of:

    :
    2016/07/20 14:44:29 "GET ... HTTP/1.1
    Host: localhost:8088
    Accept: */*
    User-Agent: curl/7.43.0
    
    "
    2016/07/20 14:44:29 ...[response body]
    :
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测