http - 如何在 POST 请求中获取参数
问题描述
我正在尝试获取 POST 请求中的参数,但我无法做到,我的代码是:
package main
import (
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", hello)
fmt.Printf("Starting server for testing HTTP POST...\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
func hello(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.Error(w, "404 not found.", http.StatusNotFound)
return
}
switch r.Method {
case "POST":
// Call ParseForm() to parse the raw query and update r.PostForm and r.Form.
if err := r.ParseForm(); err != nil {
fmt.Fprintf(w, "ParseForm() err: %v", err)
return
}
name := r.Form.Get("name")
age := r.Form.Get("age")
fmt.Print("This have been received:")
fmt.Print("name: ", name)
fmt.Print("age: ", age)
default:
fmt.Fprintf(w, "Sorry, only POST methods are supported.")
}
}
我正在终端中发出 POST 请求,如下所示:
curl -X POST -d '{"name":"Alex","age":"50"}' localhost:8080
然后输出是:
This have been received:name: age:
为什么它不采用参数?我做错了什么?
解决方案
当您将 body 作为json
对象传递时,您最好定义一个Go
与该对象匹配的结构并将 body 解码request
为对象。
type Info struct {
Name string
Age int
}
info := &Info{}
if err := json.NewDecoder(r.Body).Decode(info); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_ = json.NewEncoder(w).Encode(info)
您可以在此处找到完整的工作代码。
$ curl -X POST -d '{"name":"Alex","age":50}' localhost:8080
这个POST
请求现在工作正常。
您可以根据需要修改Go
结构和响应object
。
推荐阅读
- javascript - 当滑块值与初始值相同时,如何触发 html 输入类型 = 范围的更改事件
- html - 我想做一个关闭的 Div 框,但不知道如何
- python - 正确绘制 datetime64[ns] 到图形
- javascript - jQuery:带有装饰的可切换路径式导航
- linux - vim:调整拆分窗口大小的快捷方式
- mysql - Word 边界在 MySQL 8.0.16 REGEX 中不起作用?
- pytorch - 在detectron2 中不支持GPU 编译
- php - 通过在 Laravel 中连接两个表来对列进行排序
- java - 未设置 JAVA_HOME。(RuntimeError) 在 WSL 中为 ruby 安装 rjb gem 时
- mysql - 如何删除与第二个表中的行不匹配的表行