问题
在使用gin框架时(其他框架或原生request也类似)遇到需要先读取body再把body作为参数传给其他函数或方法处理的情况,但用
c.ShouldBindJSON()
读取body后,再次读取body为空或出错。
解决方案
利用 ioutil包提供的以下函数
// ReadAll reads from r until an error or EOF and returns the data it read.
// A successful call returns err == nil, not err == EOF. Because ReadAll is
// defined to read from src until EOF, it does not treat an EOF from Read
// as an error to be reported.
func ReadAll(r io.Reader) ([]byte, error)
// NopCloser returns a ReadCloser with a no-op Close method wrapping
// the provided Reader r.
func NopCloser(r io.Reader) io.ReadCloser
具体代码参考如下:
var receiveBody XXX
bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
err := json.Unmarshal(bodyBytes, &receiveBody)
if err != nil {
...........
return
}
c.Request.Body.Close() // must close
c.Request.Body=ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
c.Set("aaa", aaa)
此外,如以上代码所示,可以用c.Set()
写入键值对,后续可以用c.GetString("aaa")
方式获得该值。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。