在Go中解码请求体时,为什么会出现EOF错误?

huangapple go评论104阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2014年6月9日 07:20:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/24111888.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定