如何从Go上的请求主体获取JSON

如何从Go上的请求主体获取JSON,第1张

如何从Go上的请求主体获取JSON

TIL

http.Response.Body
是一个缓冲区,这意味着一旦读取它,就不能再次读取它。

就像水流一样,您可以看到它并在流过时对其进行测量,但是一旦流失,它就消失了。

但是,知道这一点,有一种解决方法,您需要“捕获”主体并将其还原:

// Read the Body contentvar bodyBytes []byteif context.Request().Body != nil {    bodyBytes, _ = ioutil.ReadAll(context.Request().Body)}// Restore the io.ReadCloser to its original statecontext.Request().Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))// Continue to use the Body, like Binding it to a struct:order := new(models.GeaOrder)error := context.Bind(order)

现在,您可以在

context.Request().Body
其他地方使用。

资料来源:

http://grokbase.com/t/gg/golang-nuts/12adq8a2ys/go-nuts-re-reading-http-
response-body-or-any-reader

https://medium.com/@xoen/golang-read-from-an-io-readwriter-without-loosing-
its-content-2c6911805361



欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5476418.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-12
下一篇2022-12-12

发表评论

登录后才能评论

评论列表(0条)

    保存