如何从http.ResponseWriter获取数据以进行日志记录

huangapple go评论154阅读模式
英文:

How to get data from http.ResponseWriter for logging

问题

我不知道这个问题是否有意义,但我想知道是否有办法获取写在http.ResponseWriter中的数据。我需要它用于日志记录。

我在Go中编写了一个API。

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) // 我正在记录请求
    result, err := compute()                 // 从函数中获取结果

    if err != nil {
        errRes := ErrorResponse{"ERROR", err}
        response, er = json.Marshal(errRes) // 获取错误响应
    } else {
        response, er = json.Marshal(result)
    }
    if er != nil {
        http.Error(w, er.Error(), 500) // 写入错误
        return
    }
    io.WriteString(w, string(response)) // 写入响应
}

目标是创建一个包含请求和响应数据的单个日志。响应可以是错误响应或处理后的响应。

我在想如果我能够获取写在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 Go.

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

得分: 14

你可以使用io.MultiWriter来实现,它可以创建一个写入器,将写入的内容复制到所有提供的写入器中。所以要记录响应,你可以这样做:

func api1(w http.ResponseWriter, req *http.Request) {
    var log bytes.Buffer
    rsp := io.MultiWriter(w, &log)
    // 从这一点开始使用 rsp 替代 w,例如
    err := json.NewDecoder(req.Body).Decode(&requestData)
    if err != nil {
        writeError(rsp, "JSON request is not in correct format")
        return
    }
    ...
}

现在,你在 rsp 中写入的信息会同时复制到 wlog 中,你可以将 log 缓冲区的内容保存到磁盘上或在控制台上显示。

你可以使用io.TeeReader创建一个读取器,它会将从给定读取器读取的内容写入给定的写入器,这样可以将 req.Body 的副本保存到日志中,例如:

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

现在,由于 JSON 解码器从 tee 中读取内容,req.Body 的内容也会被复制到 log 缓冲区中。

英文:

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.

答案2

得分: 2

补充到接受的答案中。

我喜欢使用io.MultiWriter,但它只在这个上下文中写入响应体。

如果你想要头部信息,可以使用.Headers().Write函数,像这样...

func (w http.ResponseWriter, req *http.Request) {
    var log bytes.Buffer
    rsp := io.MultiWriter(w, &log)
    // 从这一点开始使用rsp代替w,例如

    // 获取响应头部信息
    w.Header().Write(&log)

    err := json.NewDecoder(req.Body).Decode(&requestData)
    if err != nil {
        writeError(rsp, "JSON请求格式不正确")
        return
    }
    ...
}
英文:

Adding to accepted answer.

I love using io.MultiWriter, however it only writes the response body in this context.

If you want the headers, use the .Headers().Write function like this...

func (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

    // get the response headers
    w.Header().Write(&log)

    err := json.NewDecoder(req.Body).Decode(&requestData)
    if err != nil {
        writeError(rsp, "JSON request is not in correct format")
        return
    }
    ...
}

huangapple
  • 本文由 发表于 2017年5月5日 17:52:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/43801849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定