2 回答

TA貢獻1786條經驗 獲得超11個贊
如果您打印出請求的正文/標頭,則問題出在 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表示您的數據:
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 服務器端的標頭,以確保獲得所需的編碼(在本例中application/json)。

TA貢獻1848條經驗 獲得超6個贊
我認為你需要一個結構來解組數據。我認為這段代碼可以幫助你。
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 關注
- 127 瀏覽
添加回答
舉報