2

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?

Ria
  • 10,237
  • 3
  • 33
  • 60
Chris
  • 1,231
  • 1
  • 17
  • 35
  • It probably means some other piece of code has already read the request body. Without knowing what the rest of the program is doing, it is hard to say where exactly. – James Henstridge Jun 09 '14 at 02:30
  • I'll double check with that in mind, but I'm reasonably certain that method is the only one where I'm reading a request body right now. – Chris Jun 09 '14 at 14:15
  • I'm not familiar with the beego framework you're using. It might be worth checking whether it is reading the request body itself. – James Henstridge Jun 09 '14 at 15:07

1 Answers1

4

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.

Will Krause
  • 626
  • 6
  • 12