dqjcb132285 2017-10-12 16:24
浏览 68
已采纳

无法在golang中解封json python后的请求

Here is my python code (client side) :

import requests
import json
import datetime
headers = {'Content-type': 'application/json',"Authorization":"Bearer MYREALLYLONGTOKENIGOT" }
url = 'http://127.0.0.1:9210/59c94c860a52840958543027/comment/59dea421c26d684270e9321e'
data = { 'sender' : '59c94c860a52840958543027', 'receiver':'59dea421c26d684270e9321e',
        'score' :5,
        'text':'tres jolie 2'}
data_json = json.dumps(data)
r = requests.post(url=url,headers=headers,json=data_json)
r.json()

And here is my golang server side code :

type CommentSent struct {
    Sender    string `json:"sender,omitempty"`
    Receiver  string `json:"receiver,omitempty"`
    Score     int `json:"score,omitempty"`
    Text      string `json:"text,omitempty"`
}


func PostComment(w http.ResponseWriter, r *http.Request) {
    var token string
    token = getToken(r)
    fmt.Println(token)
    vars := mux.Vars(r)
    idUser := vars["idUser"]
    idUserReceiver := vars["idUserReceiver"]
    fmt.Println(idUser)
    fmt.Println(idUserReceiver)
    var commentSend = CommentSend{}
    // body, err := ioutil.ReadAll(r.Body)
    // log.Println(string(body))
    decoder := json.NewDecoder(r.Body)
    err := decoder.Decode(&commentSend)
    if (err != nil){
        Info.Println("error")
        Info.Println(err)

    }

here is what give me the commented lines :

2017/10/12 18:21:29 "{\"sender\": \"59c94c860a52840958543027\", \"score\": 5, \"receiver\": \"59dea421c26d684270e9321e\", \"text\": \"tres jolie 2\"}"

and here is the error that i get :

INFO: 2017/10/12 18:22:32 comment.go:235: json: cannot unmarshal string into Go value of type main.CommentSent

And i don't understand why i have this error the json and python part seems correct and also the golang server side seems also correct.

  • 写回答

2条回答 默认 最新

  • douzhuo6931 2017-10-12 16:33
    关注

    Your entire request body is a quoted JSON string, rather than raw JSON.

    "{\"sender\":....
    

    Either send raw JSON, i.e.:

    {"sender":...
    

    Or un-escape it in your Go program. Sending raw JSON is probably the better solution. How to do that, I don't know, as I'm not a Python guru.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误