从 bash 到 GO 服务器的 REST post 查询有效但对 Python 失败

REST post query to GO server from bash works but fails for Python

我有 go server 解组它收到的 json。 当我使用 curl 时它有效但在 python.

的情况下失败

Go 服务器解组代码:

type Data struct {
    Namespace   string `json:"namespace"`
    ContainerId string `json:"containerId"`
}
func notify(w http.ResponseWriter, r *http.Request) {
  decoder := json.NewDecoder(r.Body)
  var data Data
  err := decoder.Decode(&data)
  if err != nil {
    glog.Errorf("Failed to decode the request json %s \n", err.Error())
    return
  }
  ...
}

如果我执行 curl 命令,它会毫无怨言地工作:

curl -i -H "Accept: application/json" -H "Content-Type:application/json" -X POST --data '{"namespace": "default", "containerId": "2f7c58d399f2dc35fa1be2abea19301c8e74973ddd72f55a778babf01db5ac26"}' http://mysvc:8080/notify

但是如果我对 Python 做同样的事情,它会抱怨:

jsonPrep['containerId'] = "2f7c58d399f2dc35fa1be2abea19301c8e74973ddd72f55a778babf01db5ac26"
jsonPrep['namespace'] = "default" 
headers = {'Content-type': 'application/json', 'Accept': 'application/json'}
r = requests.post('http://mysvc:8080/notify', json=json.dumps(jsonPrep), headers=headers)

go server 抱怨:

E1026 15:49:48.974117       1 main.go:59] Failed to decode the request json json: cannot unmarshal string into Go value of type main.Data

当我执行 curlpython 中的其余查询时,我看不出有什么不同。

谁能帮我找出问题所在?

requests.post()json 参数用于传递尚未调用 json.dumps() 的值。 requestsjson 参数本身上调用 json.dumps(),所以因为你传递的是 json=json.dumps(jsonPrep)jsonPrep 最终会被 JSONified 两次,这不是你想要的想要。

或者使用 data:

requests.post(..., data=json.dumps(jsonPrep), ...)

或去掉 json.dumps():

requests.post(..., json=jsonPrep, ...)