如何解决如何访问POST请求中的嵌入式键值
我正在用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请求。请求正文为:
bets=amount&bets=position&bets=amount&bets=position
问题是'amount'
和'position'
键的值不存在。
我的问题是-如何发出/处理POST请求,以便能够访问Go服务器上处理程序函数中嵌入键'amount'
和'position'
的值,以便我可以将这些信息放入一个结构实例中。
解决方法
如果您打印出请求的正文/标头,则问题出在python端:
<style>
.card {
box-shadow: 0 4px 8px 0 rgba(0,0.2);
transition: 0.3s;
width: 40%;
height: 300px;
background-image: url("img_avatar.png");
}
.container {
padding: 2px 16px;
}
</style>
</head>
<body>
<div class="card">
<div class="container">
<h4><b>John Doe</b></h4>
<p>Architect & Engineer</p>
</div>
</div>
print requests.Request('POST',url,data=myobj).prepare().body
print requests.Request('POST',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',json=myobj).prepare().body
print requests.Request('POST',json=myobj).prepare().headers
# {"bets": [{"position": [0,1,2],"amount": 10},{"position": [10],"amount": 20}]}
# {'Content-Length': '83','Content-Type': 'application/json'}
最后,值得检查Go服务器端的x = requests.post(url,json = myobj) // `json` not `data`
标头,以确保获得所需的编码(在这种情况下为Content-Type
)。
我认为您需要一种解组数据的结构。我认为这段代码可以为您提供帮助。
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()
}