当`json.NewDecoder.Decode`失败时,我该如何保存响应体?

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

How do I save the response body when `json.NewDecoder.Decode` fails?

问题

这个代码片段的要点在Go语言中相当常见:

if err := json.NewDecoder(r.Body).Decode(&mr); err != nil {
    return mr, err
}

但是,如果出现错误,我该如何获取r.Body的字符串表示形式呢?在这种情况下,将其与错误日志一起包含在内会更有优势,而不是仅通过结构体来查找Zip有时是字符串,有时是整数。

不幸的是,在这一点上,请求体已经被关闭,所以我不确定如何再次访问它。

预先将请求体解码为字符串,然后再对其进行编码并尝试结构体映射似乎是多余的步骤。有没有更好的方法呢?

英文:

This gist of this snippet seems to be fairly common in Go:

if err := json.NewDecoder(r.Body).Decode(&mr); err != nil {
	return mr, err
}

But how do I actually retrieve a string representation of r.Body in event of an error? In this case, it would be advantageous to include this with the error log as opposed to working through the struct only to find that Zip is sometimes a string and sometimes an integer.

Unfortunately, the body has already been closed at this point, so I'm not sure how to access it again.

Preemptively decoding the body to a string, and then later encoding it and attempting the struct mapping seems like an extra step. Is there a better way?

答案1

得分: 3

如果你想保存请求体,请在解组之前保存请求体。

//...
body, err := ioutil.ReadAll(r.Body)
if err != nil {
    return err
}

err = json.Unmarshal(body, &mr)
//...
英文:

If you want to save the body, then save the body before Unmarshalling.

//...
body, err := ioutil.ReadAll(r.Body)
if err != nil {
    return err
}

err = json.Unmarshal(body, &mr)
//...

huangapple
  • 本文由 发表于 2016年12月6日 04:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/40983193.html
匿名

发表评论

匿名网友

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

确定