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 关于哈夫曼树应用得到一些问题
  • ¥15 使用sql server语句实现下面两个实验(需要代码和运行结果截图)
  • ¥20 用web解决,要给我一个完整的网页,符合上述的要求
  • ¥20 求个sql server代码和结果的图 两道题
  • ¥15 银河麒麟操作系统无法使用U盘
  • ¥100 寻找:光电二极管电路设计服务
  • ¥15 YOLOv5改进后的结构图
  • ¥15 全志v3s怎么设置高速时钟,使用的荔枝派zero开发板,串口2需要921600的波特率
  • ¥15 关于#单片机#的问题:Lora通讯模块hc-14电路图求内部原理图
  • ¥50 esp32 wroom 32e 芯片解锁