我正在尝试使用 net/http
开发一个 REST 服务。
服务接收包含所有输入参数的 JSON 结构。我想知道是否有更简单、更短的方法来实现以下内容:
func call(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
fmt.Printf("Error parsing request %s\n", err)
}
var buf []byte
buf = make([]byte, 256)
var n, err = r.Body.Read(buf)
var decoded map[string]interface{}
err = json.Unmarshal(buf[:n], &decoded)
if err != nil {
fmt.Printf("Error decoding json: %s\n", err)
}
var uid = decoded["uid"]
...
}
如您所见,仅提取第一个参数就需要相当多的行。有什么想法吗?
最佳答案
如果请求的正文将包含 JSON 结构并且您不需要任何 URL 参数,则无需调用 r.ParseForm
。
你也不需要缓冲区;你可以使用:
decoder := json.NewDecoder(r.Body)
然后:
error := decoder.Decode(decoded)
综合起来:
func call(w http.ResponseWriter, r *http.Request) {
values := make(map[string]interface{})
if error := json.NewDecoder(r.Body).Decode(&values); error != nil {
panic(error)
}
uid := values["uid"].(int)
}
不过,如果您可以在结构类型中正式定义您期望的输入结构,那就更好了:
type UpdateUserInformationRequest struct {
UserId int `json:"uid"`
// other fields...
}
并使用此结构的实例而不是更通用的映射。
关于json - 有没有更简单的方法来使用 net/http 实现 JSON REST 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23606981/