【问题标题】:How to manipulate the data that we have sent and receive in golang如何操作我们在 golang 中发送和接收的数据
【发布时间】:2018-03-17 17:52:53
【问题描述】:

如何解码已在 javascript 中发送到服务器的 json 对象 并将它们保存到变量 op1,op2,opr。

在 java 脚本中,我想解码服务器发送的响应并将其保存为变量结果。

java脚本代码:

var calculate = { 
                operand1 : null,
                operand2 : null,
                operator : null
};

function UserAction() {
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "http://localhost:8000/", true);
    xhttp.setRequestHeader("Content-type", "application/json");
    xhttp.send(calculate);
    var response = (xhttp.responseText);
    console.log(response);
}
UserAction();

转到服务器代码:

package main
import ("fmt"
        "net/http"
        "encoding/json"
)


type answer struct {
    result float64
}


func index(w http.ResponseWriter, r *http.Request) {
    ans := answer{result: 30}
    fmt.Println(r)
    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    w.Header().Set("Content-Type", "application/json; charset=UTF-8")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.WriteHeader(http.StatusOK)
    if err := json.NewEncoder(w).Encode(ans); err != nil {
        panic(err)
    }    
}

func main() {
    http.HandleFunc("/",index)
    http.ListenAndServe(":8000", nil)

}

【问题讨论】:

  • 虽然我回答了您的问题,但考虑到您之前刚刚提出的问题,这是一项非常省力的工作:stackoverflow.com/questions/49338485/… 避免这样做。花点时间阅读文档来熟悉 Go。
  • 请注意,您不能对未导出的字段进行编码或解码,例如“结果”。

标签: javascript json go request httpwebresponse


【解决方案1】:

与在 http 响应中以 json 格式编码有效负载的方式相同,您可以解码请求的正文。

err:= json.NewDecoder(request.Body).Decode(&answer);

阅读 Go 文档以备将来参考,并避免任何未明确参考文档的第三方教程。

https://golang.org/pkg/encoding/json/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 2010-12-22
    • 2017-05-29
    • 2011-09-24
    • 1970-01-01
    相关资源
    最近更新 更多