gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 20:26:07 25 4
gpt4 key购买 nike

我正在使用使用 gorilla /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);
});
}

最佳答案

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

type txData struct {
To string
From string
Value int
Key string
}

引用Golang规范 here

关于javascript - 使用提取将发布请求发送到Golang服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62231871/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com