首页 > 解决方案 > 使用 GO 网络服务器解析 POST 请求时出现问题

问题描述

我对 GO 很陌生,我正在尝试设置一个非常基本的 GO 网络服务器,到目前为止,我在处理没有任何参数的 GET 请求时没有任何问题,但是现在我正在尝试一个带有一些参数的 POST 请求,我有两个不同的问题取决于我如何发送请求。

这是处理路线的代码

func SubmitData(w http.ResponseWriter, r *http.Request) {
    reqBody, _ := ioutil.ReadAll(r.Body)

    var userInfo SubmittedUserInfo
    fmt.Println(string(reqBody))

    unmarshalErr := json.Unmarshal(reqBody, &userInfo)
    if unmarshalErr != nil {
        fmt.Println("Error Unmarshalling JSON:", unmarshalErr)
    }

    _ = json.NewEncoder(w).Encode(userInfo)

    if unmarshalErr != nil {
        log.Printf("error decoding response: %v", unmarshalErr)
        if e, ok := unmarshalErr.(*json.SyntaxError); ok {
            log.Printf("syntax error at byte offset %d", e.Offset)
        }
        log.Printf("request body: %q", reqBody)
    }

}

这是SubmittedUserInfo我尝试使用 JSON 数据创建的结构。

type SubmittedUserInfo struct {
    Number int16 `json:"Number"` // is always a number between 0 and 10
    Age int16 `json:"Age"`
    Nationality string `json:"Nationality"`
    Gender string `json:"Gender"`
    DominantHand string `json:"DominantHand"`
}

这是处理请求的函数

func handleRequests(port string) {
    muxRouter := mux.NewRouter().StrictSlash(true)
    muxRouter.HandleFunc("/", Home)
    muxRouter.HandleFunc("/health", HealthCheck)
    muxRouter.HandleFunc("/submit_data", SubmitData).Methods("POST")
    log.Fatal(http.ListenAndServe(port, muxRouter))
}

这是我得到的实际错误。如果我使用 Python 3.8 发送以下请求,则会收到相应的错误

import requests

url = "http://localhost:5050/submit_data"

args = {
    "number": 0,
    "age": 25,
    "nationality": "russian",
    "gender": "male",
    "dominantHand": "right"
}
response = requests.post(url, args)

错误:

Error Unmarshalling JSON: invalid character 'N' looking for beginning of value
2021/03/28 11:23:27 error decoding response: invalid character 'N' looking for beginning of value
2021/03/28 11:23:27 syntax error at byte offset 1
2021/03/28 11:23:27 request body: "Number=0&Age=25&Nationality=russian&Gender=male&DominantHand=right"

现在,如果我使用 Postman 发送请求,指定完全相同的参数,我会收到错误

Error Unmarshalling JSON: unexpected end of JSON input
2021/03/28 11:24:38 error decoding response: unexpected end of JSON input
2021/03/28 11:24:38 syntax error at byte offset 0
2021/03/28 11:24:38 request body: ""

我究竟做错了什么?我非常习惯在 Python 中执行此操作,如果我需要在 GO 中做一些额外的工作以确保所有内容的格式正确,我不会感到惊讶,但我不知道那可能是什么,所以任何帮助或建议都会不胜感激!

标签: python-3.xweb

解决方案


您的 python 代码正在以application/x-www-form-urlencoded格式发送数据,您可以通过查看log.Printf("request body: %q", reqBody)语句的输出来看到这一点,即:

2021/03/28 11:23:27 request body: "Number=0&Age=25&Nationality=russian&Gender=male&DominantHand=right"

不是JSON。

要使用您的 python 脚本发送 JSON,您可以执行

requests.post(url, json=args)

推荐阅读