Go语言通过net/http处理HTTP请求,GET参数用URL.Query().Get()获取并设默认值,POST请求需解析表单或解码JSON,注意验证方法、Content-Type及关闭Body,统一路由可用switch分支处理不同方法,适合RESTful设计。

Go语言处理HTTP请求非常直观,标准库net/http提供了强大且简洁的接口来处理GET和POST请求。无论是构建API还是Web服务,掌握如何正确解析不同类型的请求是关键。
GET请求通常用于获取数据,参数通过URL查询字符串传递。在Go中,可以通过http.Request对象的URL.Query()方法提取参数。
示例:
func handleGet(w http.ResponseWriter, r *http.Request) {
// 确保是GET请求
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// 获取查询参数
name := r.URL.Query().Get("name")
age := r.URL.Query().Get("age")
if name == "" {
name = "Guest"
}
fmt.Fprintf(w, "Hello %s, you are %s years old", name, age)
}
// 注册路由
http.HandleFunc("/get", handleGet)
说明:使用r.URL.Query().Get()安全获取参数,若参数不存在会返回空字符串,需做默认值处理。
立即学习“go语言免费学习笔记(深入)”;
POST请求常用于提交数据,数据体可能为表单、JSON等格式。Go能自动解析表单数据,对JSON则需要手动解码。
处理表单数据:
func handlePostForm(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Invalid method", http.StatusMethodNotAllowed)
return
}
// 解析表单(支持application/x-www-form-urlencoded)
err := r.ParseForm()
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
username := r.FormValue("username")
email := r.FormValue("email")
fmt.Fprintf(w, "Received: %s (%s)", username, email)
}
处理JSON数据:
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
func handlePostJSON(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Invalid method", http.StatusMethodNotAllowed)
return
}
// 判断Content-Type是否为application/json
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
return
}
var user User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&user); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
defer r.Body.Close()
fmt.Fprintf(w, "User: %+v", user)
}
一个路由可能需要支持多种HTTP方法,可通过判断r.Method来分支处理。
func handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
handleGet(w, r)
case "POST":
handlePostForm(w, r)
default:
http.Error(w, "Unsupported method", http.StatusMethodNotAllowed)
}
}
这种方式适合RESTful接口设计,例如同一个路径下GET获取资源,POST创建资源。
ParseForm()后才能使用FormValue()
w.Header().Set("Content-Type", "application/json")
以上就是Golang如何处理HTTP POST和GET请求_Golang HTTP方法处理技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号