英文:
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)
//...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论