从 http POST 请求解组 JSON

Unmarshalling JSON from the http POST request

我有一个用 Go 编写的简单服务器:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "io/ioutil"
    "net/http"
)

type Game struct {
    RID     string `json: "RID"`
    Country string `json: "Country"`
}

func postWaitingGames(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Println(err)
    }
    var game Game

    err = json.Unmarshal(body, &game)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%v\n", game)

    defer r.Body.Close()
}

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/wait/", postWaitingGames).Methods("POST")

    http.ListenAndServe(":8081", router)
}

和一个用 Python 编写的简单客户端用于测试目的。这是代码:

import json
import requests

json_to_send = json.dumps({"RID": "8", "Country": "Australia"})

post_headers = {'Content-type': 'application/json'}
addr = "http://127.0.0.1:8081/wait/"
resp = requests.post(url=addr, json=json_to_send, headers=post_headers)
print(resp.status_code)

并且每次客户端访问服务器时,后者都会产生此错误:

json: cannot unmarshal string into Go value of type main.Game

我知道 Handling JSON Post Request in Go

Python 版本 == 3.4 转到版本 == 1.7

提前谢谢你。

如果使用 requests.post()json 参数,您必须传递 Python dict,而不是 json-serialized 版本 -requests将负责调用 json.dumps() 。在这里你最终将你的字典序列化了两次。

此外 - 总是在使用 json 参数时 - 你不需要设置 content-type header,requests 也会处理这个问题。

因此,按照 this and this, I was getting the unmarshall error and I think you have two options using requests(当内容类型为 JSON)之类的教程后:

payload = {
    "userId": "so_cool_user",
}

A:

requests.post(url=srvc_url, json=payload)

B:

requests.post(url=srvc_url, data=json.dumps(payload))