我正在 Golang 中制作轮盘赌 REST API:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"github.com/gorilla/mux"
)
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)
s := string(reqBody)
fmt.Println(s)
}
func main() {
fmt.Println("Rest API v2.0 - Mux Routers")
handleRequests()
}
main.go
我正在使用 Python 脚本测试 POST 方法:
import requests
url = 'http://localhost:10000/spin/'
myobj = {'bets':[
{
'amount' : 10,
'position' : [0,1,2]
},
{
'amount' : 20,
'position' : [10]
}
]
}
x = requests.post(url, data = myobj)
print(x.text)
test.py
当我运行测试脚本时。服务器收到我的 POST 请求。请求正文是:
投注=金额&投注=位置&投注=金额&投注=位置
问题是 'amount'
和 'position'
键的值不存在。
我的问题是 - 如何发出/处理 POST 请求,以便能够访问嵌入键 'amount'
和 'position'
的值我在 Go 服务器上的处理程序函数,以便我可以将此信息放入结构体的实例中。
最佳答案
问题出在 python 端,如果你打印出请求的正文/ header :
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`
最后,值得检查 Go 服务器端的 Content-Type
header ,以确保获得所需的编码(在本例中为 application/json
)。
关于python - 如何访问 POST 请求中嵌入的键值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63831980/