GoLang / Javascript:在JSON POST上清空postForm和解码(正文)

时间:2016-03-22 05:42:00

标签: javascript json post go

我正在尝试将jSON数据从javascript页面发送到golang服务器,但我无法使用两端的SO接受的答案找到任何JSON数据的痕迹。

This post显示了我在Javascript中发布JSON的方式,this post显示了我尝试在Go中处理此JSON的方式。

//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 -> `{ }`
}

我不确定还有什么可以尝试的。我应该改变什么来使这项工作?

1 个答案:

答案 0 :(得分:3)

导出结构hat的字段Hat,json解码就可以了。

type Hat struct {
    Hat string // Exported field names begins with capital letters
}