On Tue, 27 Oct 2015 09:10:55 -0700 (PDT)
llewyn lew <
llewy...@gmail.com> wrote:
> This is a snippet of an ajax call I am sending.
[...]
It doesn't -- you have an error in your code somewhere.
See below.
> 2. The outputs from the last 3 lines return nothing, how can I check
> if r.Body or decoder contains the name,email,password fields passed
> from the AJAX call?
As usually, it helps breaking the problem down to the pieces which can
be debugged separate.
First, let's deal with JSON decoding.
Instead of fighting with decoding essentially unknown data -- you can't
tell for sure what exactly your jQuery sent to your server -- you
should just check JSON decoding in a controlled environment.
A simple example shows that JSON decoding works just OK: [1].
Since JSON decoding works OK, there must be something bad with the
request your AJAX is making.
There are multiple approaches to verify it.
First, you can use browser debugging tools: recent versions of Firefox
and Chrome are able to show you what's going in and out in the payloads
of requests done through AJAX.
The second approach is to temporarily write the request's body to a
file in your HTTP handler, and inspect it afterwards.
Something like this:
if r.Method == "POST" {
f, err := os.OpenFile("/tmp/blah",
os.O_CREATE | os.O_WRONLY | os.O_TRUNC, 0666)
defer f.Close()
if err != nil { ... }
io.Copy(f, r.Body)
}
Then do your request, then inspect what's there in "/tmp/blah".
The third approach is to fire up some network packet capturing program
(say, Wireshark) and sniff on the network traffic -- again, inspecting
what your browser sends. This won't work for SSL/TLS-enabled servers
(well, it's still possible to decode the traffic but requires too much
effort).
My guess on the root cause of your issue is that your AJAX actually
formats the payload of your POST request according to the
multipart/form rules -- no matter you provide a sensible value
for the Content-Type header, and set the request's object "data" member
to something which looks like JSON (and it's not JSON, it's a
JavaScript object).
[2] details how to force jQuery's AJAX wrapper to really post JSON,
and here's the helper I'm using in my own code to do that:
function postJSON (url, data) {
return $.ajax({
type: 'POST',
url: url,
contentType: 'application/json; charset=UTF-8',
data: ko.toJSON(data),
processData: false
});
};
(The ko.toJSON() function is a part of the Knockout JS framework; you
might use something built into the browser or provided by jQuery to
serialize your data to a JSON string.)
1.
http://play.golang.org/p/d-2ORhIT_A
2.
http://benjamin-schweizer.de/jquerypostjson.html