登录
首页 >  Golang >  Go问答

从 bash 到 GO 服务器的 REST post 查询可以工作,但对于 Python 则失败

来源:stackoverflow

时间:2024-03-29 19:30:34 437浏览 收藏

编程并不是一个机械性的工作,而是需要有思考,有创新的工作,语法是固定的,但解决问题的思路则是依靠人的思维,这就需要我们坚持学习和更新自己的知识。今天golang学习网就整理分享《从 bash 到 GO 服务器的 REST post 查询可以工作,但对于 Python 则失败》,文章讲解的知识点主要包括,如果你对Golang方面的知识点感兴趣,就不要错过golang学习网,在这可以对大家的知识积累有所帮助,助力开发能力的提升。

问题内容

我有 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 服务器 抱怨:

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

当我在 python 中执行 curl 与其余查询时,我看不出有什么不同。

谁能帮我找出问题所在吗?


解决方案


json 参数 requests.post() 用于传递尚未有 json.dumps() 调用的值。 requestsjson 参数本身上调用 json.dumps() ,因此因为您传递 json=json.dumps(jsonprep),所以 jsonprep 最终将被 json 化两次,这不是您想要的。

使用 data

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

或者删除 json.dumps():

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

终于介绍完啦!小伙伴们,这篇关于《从 bash 到 GO 服务器的 REST post 查询可以工作,但对于 Python 则失败》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>