从http POST请求解组JSON

时间:2017-01-05 13:17:31

标签: python json http go marshalling

我有一个用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

提前谢谢。

2 个答案:

答案 0 :(得分:3)

如果使用requests.post()的{​​{1}}参数,则必须传递Python json,而不是json序列化版本 - dict将会调用{{1} }} 在上面。在这里,你最终会将你的dict序列化两次。

此外 - 总是在使用requests参数时 - 您不需要设置内容类型标题,json.dumps()也会处理此问题。

答案 1 :(得分:0)

因此,在遵循诸如thisthis之类的一些教程之后,我遇到了 unmarshall 错误,并且我认为使用 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))