douxieshang5577 2017-05-05 09:52
浏览 1466
已采纳

Golang:从http.ResponseWriter获取数据进行记录

I don't know if this question makes any sense, but I was wondering If there is any way to get the data which is written in http.ResponseWriter. I need it for logging.

I have written an api in Golang.

func api1(w http.ResponseWriter, req *http.Request) {       
    var requestData MyStruct
    err := json.NewDecoder(req.Body).Decode(&requestData)
    if err != nil {
        writeError(w, "JSON request is not in correct format")
        return
    }
    log.Println(" Request Data :", req.Body) // I am logging req
    result, err := compute()                 // getting result from a function

    if err != nil {
        errRes := ErrorResponse{"ERROR", err}
        response, er = json.Marshal(errRes) // getting error response
    } else {
        response, er = json.Marshal(result)
    }
    if er != nil {
        http.Error(w, er.Error(), 500) // writing error
        return
    }
    io.WriteString(w, string(response)) // writing response
}

The aim is to create a single log with request and response data. The response can be either an error response or processed response.

I was thinking if I could get data which is written on http.ResponseWriter then, I can create single meaningful log.

Is this possible? If not, please suggest how can I achieve this.

  • 写回答

1条回答 默认 最新

  • dqftyn1717 2017-05-05 11:38
    关注

    You could use io.MultiWriter - it creates a writer that duplicates its writes to all the provided writers. So to log the reponse

    func api1(w http.ResponseWriter, req *http.Request) {
        var log bytes.Buffer
        rsp := io.MultiWriter(w, &log)
        // from this point on use rsp instead of w, ie
        err := json.NewDecoder(req.Body).Decode(&requestData)
        if err != nil {
            writeError(rsp, "JSON request is not in correct format")
            return
        }
        ...
    }
    

    Now you have duplicate of the info written into rsp in both w and log and you can save the content of the log buffer onto disc of show it on console etc.

    You can use io.TeeReader to create a Reader that writes to given Writer what it reads from given reader - this would allow you to save copy of the req.Body into log, ie

    func api1(w http.ResponseWriter, req *http.Request) {
        var log bytes.Buffer
        tee := io.TeeReader(req.Body, &log)
        err := json.NewDecoder(tee).Decode(&requestData)
        ...
    }
    

    Now since json decoder reads form tee the content of the req.Body is also copied into the log buffer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能