-1

I'm trying to POST JSON data from a javascript page, into a golang server, but I'm unable to find any trace of the JSON data using the SO accepted answers on both ends.

This post shows the way I'm posting my JSON in Javascript and this post shows the way I'm trying to process this JSON in Go.

//js json post send
var request = new XMLHttpRequest();
request.open('POST', 'http://localhost:8080/aardvark/posts', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

var data = {hat: "fez"};
request.send(JSON.stringify(data));

The header below was set from this answer

//Go json post response
func reply(w http.ResponseWriter, r *http.Request) {

    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Credentials", "true")
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
    w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT")


    if err := r.ParseForm(); err != nil {
        fmt.Println(err);
    }

    //this is my first impulse.  It makes the most sense to me.
    fmt.Println(r.PostForm);          //out -> `map[]`  would be `map[string]string` I think
    fmt.Println(r.PostForm["hat"]);   //out -> `[]`  would be `fez` or `["fez"]`
    fmt.Println(r.Body);              //out -> `&{0xc82000e780 <nil> <nil> false true {0 0} false false false}`


    type Hat struct {
        hat string
    }

    //this is the way the linked SO post above said should work.  I don't see how the r.Body could be decoded.
    decoder := json.NewDecoder(r.Body)
    var t Hat   
    err := decoder.Decode(&t)
    if err != nil {
        fmt.Println(err);
    }
    fmt.Println(t);                  //out -> `{ }`
}

I'm not really sure what else to try from here. What should I change to make this work?

Community
  • 1
  • 1
Seph Reed
  • 8,797
  • 11
  • 60
  • 125
  • 1
    You're right in using `r.Body`. The reason that it looks so strange when you print it is that you're printing the structure that will let you read the posted contents (that is, the `io.Reader`) rather than the actual contents. – djd Mar 22 '16 at 05:48
  • 1
    `ParseForm` would not work because it expects the encoding to be `application/x-www-form-urlencoded` or `multipart/form-data` which are different to json – Aruna Herath Mar 22 '16 at 06:02

1 Answers1

3

Export the field hat of the struct Hat and json decoding would work.

type Hat struct {
    Hat string // Exported field names begins with capital letters
}
Aruna Herath
  • 6,241
  • 1
  • 40
  • 59
  • 1
    For the full details see the [docs for Unmarshal](https://golang.org/pkg/encoding/json/#Unmarshal): Unmarshal unmarshals into structs "preferring an exact match but also accepting a case-insensitive match. Unmarshal will only set exported fields of the struct" – djd Mar 22 '16 at 05:52