英文:
Decoding a request body in Go -- Why am I getting an EOF?
问题
我正在使用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 {
//处理数据
} else {
//告诉我长度、读取的字节数和错误信息
}
}
根据这个教程,上述代码应该可以正常工作。
我的问题是:bytesRead, err := this.Ctx.Request.Body.Read(p)
返回的读取字节数为0,而err.Error()
为EOF
。
然而,request.ContentLength
是一个合理的字节数(根据我输入的数据而定,至少为19个字节)。
我无法理解为什么请求的长度看起来是有的,但在Read
操作上却失败了。有什么想法吗?
英文:
I'm using the Beego framework to build a web application, and I'm trying to hand it some JSON encoded data. Roughly, this is what I have:
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
}
}
Per this tutorial, the above Should Just Work (tm).
My problem is this: bytesRead, err := this.Ctx.Request.Body.Read(p)
is returning 0 bytes read and the err.Error()
is EOF
.
The request.ContentLength
, however, is a sane number of bytes (19 or more, depending on what data I type in).
I can't figure out why the request would appear to have some length, but would fail on Read
. Any ideas?
答案1
得分: 4
如果你想在Beego中获取JSON负载,你需要调用:
this.Ctx.Input.RequestBody
它会返回一个[]byte数组,其中包含发送的负载数据。然后,你可以将它传递给一个函数,例如:
var datapoint Datapoint
json.Unmarshal(this.Ctx.Input.RequestBody, &datapoint)
其中datapoint是你尝试将数据解组成的结构体。
英文:
If you are trying to reach a JSON payload in Beego, you'll want to call
this.Ctx.Input.RequestBody
That returns a []byte array of the sent payload. You can then pass it to a function like:
var datapoint Datapoint
json.Unmarshal(this.Ctx.Input.RequestBody, &datapoint)
Where datapoint is the struct you are attempting to unmarshall your data into.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论