Go语言通过encoding/json和net/http包实现JSON处理,1. 使用json.NewDecoder解析请求体到结构体;2. 用json.NewEncoder或json.Marshal返回JSON响应;3. 通过struct标签自定义字段映射;4. 可用map[string]interface{}处理未知结构。

在Go语言中处理JSON请求与响应是Web开发中的常见需求,特别是在构建RESTful API时。Golang通过标准库encoding/json提供了强大且简洁的支持,结合net/http包可以轻松实现JSON数据的解析与序列化。
当客户端发送JSON格式的数据到服务器时,你需要将请求体中的JSON数据解析为Go结构体。使用json.Unmarshal方法即可完成这一操作。
示例:定义结构体并解析请求
type User struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}
<p>func createUser(w http.ResponseWriter, r *http.Request) {
var user User
// 读取请求体
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "无法读取请求体", http.StatusBadRequest)
return
}
defer r.Body.Close()</p><pre class='brush:php;toolbar:false;'>// 解析JSON
if err := json.Unmarshal(body, &user); err != nil {
http.Error(w, "无效的JSON格式", http.StatusBadRequest)
return
}
// 使用解析后的数据
fmt.Printf("收到用户: %+v\n", user)}
立即学习“go语言免费学习笔记(深入)”;
简化方式:直接解码
你也可以使用json.NewDecoder直接从r.Body解码,节省内存:
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
http.Error(w, "解析JSON失败", http.StatusBadRequest)
return
}
将Go数据结构转换为JSON并返回给客户端,使用json.Marshal或json.NewEncoder。
示例:返回JSON响应
func getUser(w http.ResponseWriter, r *http.Request) {
user := User{
Name: "Alice",
Email: "alice@example.com",
Age: 30,
}
<pre class='brush:php;toolbar:false;'>w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(user); err != nil {
http.Error(w, "生成JSON失败", http.StatusInternalServerError)
}}
立即学习“go语言免费学习笔记(深入)”;
说明:
- 设置Content-Type: application/json是良好实践。
- json.NewEncoder(w).Encode()会自动添加换行,适合流式输出。
Go结构体字段默认使用字段名作为JSON键,但通常需要自定义。通过json:标签可以指定映射关系。
type Product struct {
ID int `json:"id"`
Title string `json:"title"`
Price float64 `json:"price"`
IsAvailable bool `json:"in_stock"` // 自定义字段名
SecretKey string `json:"-"` // 不导出该字段
}
使用"-"可以忽略某些敏感字段,防止意外暴露。
如果不知道JSON的具体结构,可以使用map[string]interface{}或interface{}接收。
var data map[string]interface{}
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
http.Error(w, "无效JSON", http.StatusBadRequest)
return
}
fmt.Println(data["name"], data["age"])
适用于Webhook、配置接收等场景,但需注意类型断言安全。
基本上就这些。Golang对JSON的支持简洁高效,配合结构体和标准库就能满足大多数Web服务需求。关键在于正确使用结构体标签、错误处理和内容类型设置。
以上就是如何用Golang处理JSON请求与响应_Golang JSON请求响应使用方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号