You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go服务端无法解析HTTP POST请求JSON内容问题求助

问题解决:Go服务端无法解析POST请求的JSON内容

问题现象

POST请求能正常到达Go服务端,但解析后Authentication结构体的username和password字段始终为空,服务端输出内容为:

Received authentication: {username: password:}

服务端原代码

package main

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

type Authentication struct {
    username string 
    password string
}

func main() {

    mux := http.NewServeMux()

    mux.HandleFunc("/auth", func(w http.ResponseWriter, req *http.Request) {
        decoder := json.NewDecoder(req.Body)
        var auth Authentication
        err := decoder.Decode(&auth)

        if err != nil {
            http.Error(w, "Failed to decode JSON", http.StatusBadRequest)
            return
        }

        fmt.Printf("Received authentication: %+v\n", auth)
    })

    mux.Handle("/",http.FileServer(http.Dir("./static")))

    fmt.Printf("Starting server at port 3000\n")

    http.ListenAndServe(":3000", mux)
}

客户端原代码

//--Variables--//
let signin = document.getElementById("Signin");
let username = document.getElementById("Username");
let password = document.getElementById("Password");

signin.onclick = () => {
  let data = {
    username: username.value,
    password: password.value,
  };
  sendData("/auth", data);
  console.log(data.username, "   ", data.password);
};

//--Functions--//
const sendData = (url, data) => {
fetch(url, {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
};

问题原因

Go语言的可见性规则规定:结构体字段首字母小写时属于私有字段,仅能在当前包内访问;而encoding/json属于外部包,无法读取私有字段,因此JSON解码时无法将请求体中的值赋值给这些字段,最终导致字段为空。

解决方案

将Authentication结构体的字段改为首字母大写的导出字段,并通过JSON标签映射客户端传来的小写key:

type Authentication struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

修改后,encoding/json包就能正确识别并解析请求体中的JSON内容,将对应的值赋值给结构体字段。

内容的提问来源于stack exchange,提问作者Kilian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 01:35:03