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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀