duanpan7011 2017-01-05 13:17
浏览 56
已采纳

从http POST请求中解组JSON

I have a simple server written in Go:

package main

import (
    "encoding/json"
    "fmt"
    "github.com/gorilla/mux"
    "io/ioutil"
    "net/http"
)

type Game struct {
    RID     string `json: "RID"`
    Country string `json: "Country"`
}

func postWaitingGames(w http.ResponseWriter, r *http.Request) {
    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
        fmt.Println(err)
    }
    var game Game

    err = json.Unmarshal(body, &game)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%v
", game)

    defer r.Body.Close()
}

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/wait/", postWaitingGames).Methods("POST")

    http.ListenAndServe(":8081", router)
}

And a simple client written in Python for testing purposes. Here's the code:

import json
import requests

json_to_send = json.dumps({"RID": "8", "Country": "Australia"})

post_headers = {'Content-type': 'application/json'}
addr = "http://127.0.0.1:8081/wait/"
resp = requests.post(url=addr, json=json_to_send, headers=post_headers)
print(resp.status_code)

and everytime the client hits the server, the latter yields this error:

json: cannot unmarshal string into Go value of type main.Game

I'm aware of Handling JSON Post Request in Go

Python version == 3.4 Go version == 1.7

Thank you in advance.

  • 写回答

1条回答 默认 最新

  • dsf5632 2017-01-05 13:23
    关注

    If using requests.post()'s json argument, you must pass you Python dict, not the json-serialized version -requests will take care of calling json.dumps() on it. Here you end up having your dict serialized twice.

    Also - always when using the json argument - you don't need to set the content-type header, requests will take care of this too.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看