我的客户端代码向服务器发送一条AJAX请求,其中包含一条消息
我如何从该请求消息正文中读取数据。在Express of NodeJS中,我使用了这个:
app.post('/api/on', auth.isLoggedIn, function(req, res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'POST');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
var url = req.body.url;
// Later process
}
Go中的url = req.body.url
等价物是什么?
答案 0 :(得分:2)
如果请求正文是URL编码的,那么使用r.FormValue("url")来获取" url"来自请求的价值。
如果请求正文是JSON,则使用JSON decoder将request body解析为键入的值以匹配JSON的形状。
var data struct {
URL string
}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
// handle error
}
// data.URL is "url" member of the posted JSON object.
答案 1 :(得分:1)
Here是一个简单的http处理程序示例:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
func main() {
http.HandleFunc("/", Handler)
http.ListenAndServe(":8080", nil)
// Running in playground will fail but this will start a server locally
}
type Payload struct {
ArbitraryValue string `json:"arbitrary"`
AnotherInt int `json:"another"`
}
func Handler(w http.ResponseWriter, r *http.Request) {
body, err := ioutil.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
url := r.URL
// Do something with Request URL
fmt.Fprintf(w, "The URL is %q", url)
payload := Payload{}
err = json.NewDecoder(bytes.NewReader(body)).Decode(&payload)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Do something with payload
}