2 回答
TA贡献1865条经验 获得超7个赞
如果请求正文是 URL 编码的,则使用r.FormValue("url")从请求中获取“url”值。
如果请求正文是 JSON,则使用JSON 解码器将请求正文解析为键入的值以匹配 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.
TA贡献1828条经验 获得超3个赞
这是一个简单的 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
}
- 2 回答
- 0 关注
- 238 浏览
添加回答
举报