vendredi 26 décembre 2014

Golang net/http request Body always empty

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.





Aucun commentaire:

Enregistrer un commentaire