Golang net / http request Body is always empty

I am trying to send JSON arguments to my server and parse them using json.Decoder. I read that you should be able to get the request parameters from the request.Body property. Below is the 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>

(timestamps, of course). My client AJAX call looks like this:

$.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);
  }
});

      

Example URL of a sent message:

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

      

Nice to look at the parameters:

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

      

I have tried with GET and POST requests.

Why is my req.Body never decoded? If I try to print just req.Body I also see nil.

+3


source to share


2 answers


req.Body

is really empty - so that I would do this, call req.ParseForm()

and then use req.Form

. Body

will not receive stuff (like request parameters) that is definitely not in the request body.



+4


source


Body

the request is sent inside the payload - it is not part of the url.

You are trying to access the body .. when indeed your data is in the url.



What do you want to change the ajax method: "get"

how method: "post"

- so that the data is sent 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 through your browser of choice "developer tools". Also, if you really want your data to be sent together as part of the url, you have to access the URL

request parameter - and manually parse the values ​​in the structure (the json package won't do that for you IIRC).

0


source







All Articles