2 回答

TA貢獻(xiàn)1786條經(jīng)驗 獲得超11個贊
如果您打印出請求的正文/標(biāo)頭,則問題出在 python 方面:
print requests.Request('POST', url, data=myobj).prepare().body
print requests.Request('POST', url, data=myobj).prepare().headers
# bets=position&bets=amount&bets=position&bets=amount
# {'Content-Length': '51', 'Content-Type': 'application/x-www-form-urlencoded'}
data使用x-www-form-urlencoded編碼,因此需要一個鍵/值對的平面列表。
您可能想要json表示您的數(shù)據(jù):
print requests.Request('POST', url, json=myobj).prepare().body
print requests.Request('POST', url, json=myobj).prepare().headers
# {"bets": [{"position": [0, 1, 2], "amount": 10}, {"position": [10], "amount": 20}]}
# {'Content-Length': '83', 'Content-Type': 'application/json'}
使固定:
x = requests.post(url, json = myobj) // `json` not `data`
最后,值得檢查Content-TypeGo 服務(wù)器端的標(biāo)頭,以確保獲得所需的編碼(在本例中application/json)。

TA貢獻(xiàn)1848條經(jīng)驗 獲得超6個贊
我認(rèn)為你需要一個結(jié)構(gòu)來解組數(shù)據(jù)。我認(rèn)為這段代碼可以幫助你。
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"io/ioutil"
"log"
"net/http"
)
type Body struct {
Bets []Persion `json:"bets"`
}
type Persion struct{
Amount int `json:"amount"`
Position []int `json:"position"`
}
func handleRequests() {
// creates a new instance of a mux router
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/spin/", handler).Methods("POST")
log.Fatal(http.ListenAndServe(":10000", myRouter))
}
func handler(w http.ResponseWriter, r *http.Request) {
reqBody, _ := ioutil.ReadAll(r.Body)
bodyObj :=&Body{}
err:=json.Unmarshal(reqBody,bodyObj)
if err!=nil{
log.Println("%s",err.Error())
}
//s := string(reqBody)
fmt.Println(bodyObj.Bets[0].Amount)
}
func main() {
fmt.Println("Rest API v2.0 - Mux Routers")
handleRequests()
}
- 2 回答
- 0 關(guān)注
- 125 瀏覽
添加回答
舉報