doupuzhimuhan9216 2016-03-22 05:41
浏览 59
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • duan88014 2016-03-22 05:47
    关注

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算