使用提取将发布请求发送到Golang服务器

时间:2020-06-06 12:41:43

标签: javascript api go fetch

我正在使用使用大猩猩/ mux的golang服务器和来自“ github.com/graarh/golang-socketio”的WebSocket服务器,我将JSON格式的数据发送到golang服务器,我想将其解析为一个结构,但它没有解析数据,请单击output for the code

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

    "github.com/gorilla/mux"
    gosocketio "github.com/graarh/golang-socketio"
    "github.com/graarh/golang-socketio/transport"
)
type txData struct {
    to    string
    from  string
    value int
    key   string
}
func createeWsSocketServer() *gosocketio.Server {
    return gosocketio.NewServer(transport.GetDefaultWebsocketTransport())
}
func transactionHandler(w http.ResponseWriter, r *http.Request) {

    fmt.Fprintf(w, "transactionHandler Hit")
    fmt.Println("endpoint hit")
    var t txData

    decoder := json.NewDecoder(r.Body)
    fmt.Println("response Body:", r.Body)
    err := decoder.Decode(&t)

    if err != nil {
        panic(err)
    }

    fmt.Printf("%+v", t)
}
func handleRequests() {
    wsServer := createeWsSocketServer()
    wsServer.On(gosocketio.OnConnection, func(c *gosocketio.Channel) {
        c.Join("room")
        wsServer.BroadcastToAll("serverEvent", "New Client Joined!")
    })

    wsServer.On("clientEvent", func(c *gosocketio.Channel, msg string) string {
        c.BroadcastTo("room", "roomEvent", msg)
        return "returns OK"
    })

    myRouter := mux.NewRouter().StrictSlash(true)
    myRouter.Handle("/", http.FileServer(http.Dir("./static")))
    myRouter.Handle("/socket.io/", wsServer)
    myRouter.HandleFunc("/transaction", transactionHandler)
    log.Panic(http.ListenAndServe(":8080", myRouter))
}
func main() {
    handleRequests()
}

这是用于调用服务器的javascript代码

document.getElementById("form").addEventListener("submit", (e) => {
        e.preventDefault();
        console.log("form submitetd");
        let file = document.getElementById("fileInput").files[0];
        let fr = new FileReader();
        fr.onload = function () {
          postData(fr.result.toString());
        };

        fr.readAsText(file);
      });

      function postData(fileString) {
        let Body = {};
        Body.key = fileString;
        Body.to = document.getElementById("to").value;
        Body.from = document.getElementById("from").value;
        Body.amount = document.getElementById("amount").value;
        console.log(Body);

        fetch("/transaction", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },

          body: JSON.stringify(Body),
        }).then((resp) => {
          console.log(resp);
        });
      }

1 个答案:

答案 0 :(得分:2)

您的sut.object结构字段未导出,这意味着它们在包外部不可见,因为它们以小写字母开头。因此txData软件包无法访问它们。将字段的首字母大写以使其导出。

encoding/json

参考Golang规范here