登录
首页 >  Golang >  Go问答

向Golang服务器发送POST请求的方法:使用fetch

来源:stackoverflow

时间:2024-02-20 23:15:22 335浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《向Golang服务器发送POST请求的方法:使用fetch》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我正在使用使用 gorilla/mux 的 golang 服务器和来自“github.com/graarh/golang-socketio”的 websocket 服务器,我以 json 的形式将数据发送到 golang 服务器,我想将其解析为一个结构,但它不解析数据:

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

到这里,我们也就讲完了《向Golang服务器发送POST请求的方法:使用fetch》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>