在Golang中解析HTTP请求需使用*http.Request对象,首先通过r.Header.Get获取请求头,再用r.URL.Query()处理URL参数,接着调用r.ParseForm()解析表单数据并从r.Form或r.PostForm读取,最后通过json.NewDecoder(r.Body).Decode(&struct)处理JSON等结构化请求体。

在Golang中处理HTTP请求,解析请求头和参数是日常开发的基础。核心在于利用
*http.Request
r.Header
map[string][]string
r.URL.Query()
url.Values
r.ParseForm()
r.Form
r.PostForm
encoding/json
encoding/xml
r.Body
在Golang的HTTP处理函数中,我们与请求的交互主要围绕
*http.Request
1. 解析HTTP请求头 (Headers)
r.Header
http.Header
map[string][]string
content-type
content-type
立即学习“go语言免费学习笔记(深入)”;
r.Header.Get("Header-Name")r.Header["Header-Name"]
[]string
package main
import (
"fmt"
"net/http"
)
func headerHandler(w http.ResponseWriter, r *http.Request) {
// 获取User-Agent头
userAgent := r.Header.Get("User-Agent")
fmt.Fprintf(w, "User-Agent: %s\n", userAgent)
// 获取Accept头的所有值
acceptHeaders := r.Header["Accept"]
fmt.Fprintf(w, "Accept Headers: %v\n", acceptHeaders)
// 尝试获取一个可能不存在的头
nonExistentHeader := r.Header.Get("X-Custom-Header")
if nonExistentHeader == "" {
fmt.Fprintf(w, "X-Custom-Header is not present.\n")
} else {
fmt.Fprintf(w, "X-Custom-Header: %s\n", nonExistentHeader)
}
}
// func main() {
// http.HandleFunc("/headers", headerHandler)
// fmt.Println("Server listening on :8080")
// http.ListenAndServe(":8080", nil)
// }2. 解析URL查询参数 (Query Parameters)
对于GET请求,参数通常附加在URL的查询字符串中(例如
/path?id=123&name=test
r.URL.Query()
url.Values
map[string][]string
q.Get("key")q["key"]
package main
import (
"fmt"
"net/http"
)
func queryHandler(w http.ResponseWriter, r *http.Request) {
queryValues := r.URL.Query()
id := queryValues.Get("id")
name := queryValues.Get("name")
tags := queryValues["tag"] // 获取所有名为"tag"的参数
fmt.Fprintf(w, "ID: %s\n", id)
fmt.Fprintf(w, "Name: %s\n", name)
fmt.Fprintf(w, "Tags: %v\n", tags) // 如果URL是 /query?tag=go&tag=web
}
// func main() {
// http.HandleFunc("/query", queryHandler)
// fmt.Println("Server listening on :8080")
// http.ListenAndServe(":8080", nil)
// }3. 解析表单参数 (Form Parameters)
对于POST、PUT等请求,表单数据通常放在请求体中,
content-type
application/x-www-form-urlencoded
multipart/form-data
r.ParseForm()
r.ParseForm()
multipart/form-data
r.ParseMultipartForm(maxMemory)
r.Form
r.PostForm
r.FormValue("key")r.PostFormValue("key")r.ParseForm()
r.FormValue
r.PostFormValue
package main
import (
"fmt"
"net/http"
)
func formHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
// 必须先调用ParseForm()
err := r.ParseForm()
if err != nil {
http.Error(w, fmt.Sprintf("Error parsing form: %v", err), http.StatusBadRequest)
return
}
// 从r.Form获取(包含URL查询参数和POST表单参数)
username := r.Form.Get("username")
password := r.Form.Get("password")
// 从r.PostForm获取(仅POST表单参数)
email := r.PostForm.Get("email")
// 使用FormValue快捷方法
age := r.FormValue("age") // 即使没ParseForm也会自动调用
fmt.Fprintf(w, "Username: %s\n", username)
fmt.Fprintf(w, "Password: %s\n", password)
fmt.Fprintf(w, "Email: %s\n", email)
fmt.Fprintf(w, "Age: %s\n", age)
}
// func main() {
// http.HandleFunc("/form", formHandler)
// fmt.Println("Server listening on :8080")
// http.ListenAndServe(":8080", nil)
// }4. 解析JSON/XML请求体 (Request Body)
当
content-type
application/json
application/xml
r.Body
io.ReadCloser
r.Body
defer r.Body.Close()
json.NewDecoder(r.Body).Decode(&yourStruct)
xml.NewDecoder(r.Body).Decode(&yourStruct)
package main
import (
"encoding/json"
"fmt"
"net/http"
"io/ioutil" // 用于读取原始请求体
)
type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"` // omitempty表示如果为空则不序列化
}
func jsonHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Only POST method is allowed", http.StatusMethodNotAllowed)
return
}
// 确保关闭请求体
defer r.Body.Close()
// 检查Content-Type
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "Content-Type must be application/json", http.StatusUnsupportedMediaType)
return
}
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, fmt.Sprintf以上就是GolangHTTP请求头与参数解析实践的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号