'Cannot unmarshal a post json python request in Go

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.



Solution 1:[1]

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.

Solution 2:[2]

I know there is an answer that covers the go side, but when it comes to Python, you shouldn't convert the dictionary to a json. The requests library should do that for you and ensures that the data is sent properly.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Flimzy
Solution 2 Bradley Robinson