Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang net/http request Body always empty

Tags:

json

go

web

I'm trying to send JSON arguments to my server and parse them using json.Decoder. I've read that you should be able to get the query params from the request.Body property. The following is my server code:

func stepHandler(res http.ResponseWriter, req *http.Request) {
    var v interface{}
    err := json.NewDecoder(req.Body).Decode(&v)
    if err != nil {
       // handle error
    }
    log.Println(v)
}

Every time, I see 2014/12/26 22:49:23 <nil> (diff timestamps, of course). My client-side AJAX call is the following:

$.ajax({
  url: "/step",
  method: "get",
  data: {
    steps: $("#step-size").val(),
    direction: $("#step-forward").prop("checked") ? 1 : -1,
    cells: JSON.stringify(painted)
  },
  success: function (data) {
    painted = data;
    redraw();
  },
  error: function (xhr) {
    console.log(xhr);
  }
});

An example URL of what is sent:

http://localhost:5000/?steps=1&direction=1&cells=%5B%7B%22row%22%3A11%2C%22column%22%3A15%7D%2C%7B%22row%22%3A12%2C%22column%22%3A15%7D%5D

A nicer look at the params:

{
  steps: "1",
  direction: "1",
  cells: "[{"row":11,"column":15},{"row":12,"column":15}]"
}

I have tried with both GET and POST requests.

Why does my req.Body never decode? If I try to print req.Body alone, I also see nil.

like image 419
Larry Price Avatar asked Dec 27 '14 03:12

Larry Price


2 Answers

req.Body is indeed empty -- so, what I would do it call req.ParseForm() and then use req.Form instead. Body will not get stuff (such as, query parameters) that's definitely not in the request's body.

like image 164
Alex Martelli Avatar answered Oct 18 '22 04:10

Alex Martelli


The Body of a request is sent along inside the payload - it is not part of the URL.

You're attempting to access the body .. when really your data is in the URL.

What you want it to change your ajax method: "get" to be method: "post" - so that the data is posted along with the body and not as part of the URL. You should also make sure that the data is indeed being sent along with the request via your browser of choice' developer tools. Alternatively, if you really do want your data sent along as part of the URL, you should be accessing the URL parameter of the request - and manually parsing the values into a struct (the json package won't do this for you IIRC).

like image 36
Simon Whitehead Avatar answered Oct 18 '22 04:10

Simon Whitehead