我正在使用 Beego 框架构建一个 Web 应用程序,并尝试向它传递一些 JSON 编码数据。粗略地说,这就是我所拥有的:
import (
"github.com/astaxie/beego"
)
type LoginController struct {
beego.Controller
}
func (this *LoginController) Post() {
request := this.Ctx.Request
length := request.ContentLength
p := make([]byte, length)
bytesRead, err := this.Ctx.Request.Body.Read(p)
if err == nil{
//blah
} else {
//tell me the length, bytes read, and error
}
}
每this tutorial ,上面的应该可以工作(tm)。
我的问题是这样的:bytesRead, err := this.Ctx.Request.Body.Read(p)
返回读取的 0 个字节,并且 err.Error()
是 EOF
。
但是,request.ContentLength
的字节数是合理的(19 或更多,具体取决于我输入的数据)。
我不明白为什么请求看起来有一定长度,但读取
却失败。有什么想法吗?
最佳答案
如果您尝试在 Beego 中获取 JSON 负载,您需要调用
this.Ctx.Input.RequestBody
返回已发送有效负载的 [] 字节数组。然后您可以将其传递给如下函数:
var datapoint Datapoint
json.Unmarshal(this.Ctx.Input.RequestBody, &datapoint)
其中 datapoint 是您尝试将数据解码到的结构。
关于json - 在 Go 中解码请求正文——为什么我会收到 EOF?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111888/