Go语言通过encoding/json和net/http包处理JSON请求与响应,需定义带标签的结构体映射JSON字段,使用json.NewDecoder解析请求体并校验Content-Type,利用json.NewEncoder编码响应数据并设置正确Header,完整示例包含POST创建用户及返回JSON结果,注意方法、媒体类型检查与错误处理。

在Go语言开发中,处理JSON格式的HTTP请求与响应是构建现代Web服务的基础能力。Golang标准库提供了encoding/json和net/http包,配合使用可以高效地完成序列化、反序列化以及网络通信。本文将通过实际示例讲解如何正确处理JSON请求与响应。
要处理JSON数据,第一步是定义与JSON字段对应的Go结构体。使用结构体标签(struct tags)来指定JSON字段名,确保字段可导出(首字母大写)以便json包能正确读取。
例如,假设客户端发送用户注册信息:
type User struct {
    ID   int    `json:"id"`
    Name string `json:"name"`
    Email string `json:"email"`
}
这里的json:"name"告诉json.Unmarshal将JSON中的name字段映射到结构体的Name字段。如果字段为空或不匹配,解析会忽略该字段而不报错。
立即学习“go语言免费学习笔记(深入)”;
在HTTP处理器中,从*http.Request读取请求体并解析为结构体对象。需要检查内容类型、读取Body并进行反序列化。
func createUser(w http.ResponseWriter, r *http.Request) {
    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)
    defer r.Body.Close()
    if err := decoder.Decode(&user); err != nil {
        http.Error(w, "invalid JSON", http.StatusBadRequest)
        return
    }
    // 处理逻辑:保存用户等
    fmt.Printf("Received user: %+v\n", user)
}
关键点:
 
                        Easily find JSON paths within JSON objects using our intuitive Json Path Finder
 30
30
                             
                    json.NewDecoder直接从r.Body流式读取,适合大体积数据且性能较好。defer r.Body.Close()释放资源。400 Bad Request,内容类型错误返回415 Unsupported Media Type。向客户端返回JSON数据时,使用json.Marshal将结构体编码为JSON字节流,并设置正确的响应头。
func getUser(w http.ResponseWriter, r *http.Request) {
    user := User{ID: 1, Name: "Alice", Email: "alice@example.com"}
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)
    if err := json.NewEncoder(w).Encode(user); err != nil {
        http.Error(w, "failed to encode response", http.StatusInternalServerError)
        return
    }
}
说明:
w.Header().Set("Content-Type", "application/json")告知客户端返回的是JSON数据。json.NewEncoder(w).Encode直接写入响应流,避免中间内存分配,效率更高。500 Internal Server Error。将上述部分整合成一个简单服务:
package main
import (
    "encoding/json"
    "log"
    "net/http"
)
type User struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Email string `json:"email"`
}
func createUser(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
        return
    }
    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)
    defer r.Body.Close()
    if err := decoder.Decode(&user); err != nil {
        http.Error(w, "invalid JSON", http.StatusBadRequest)
        return
    }
    // 模拟创建成功,返回带ID的结果
    user.ID = 123
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    json.NewEncoder(w).Encode(user)
}
func main() {
    http.HandleFunc("/users", createUser)
    log.Println("Server starting on :8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}
运行后可通过curl测试:
curl -X POST http://localhost:8080/users \
  -H "Content-Type: application/json" \
  -d '{"name":"Bob","email":"bob@example.com"}'
基本上就这些。掌握结构体标签、请求体解析、响应编码和错误处理,就能在Golang中稳健地处理JSON HTTP通信。不复杂但容易忽略细节,比如Content-Type校验和资源释放。
以上就是Golang如何处理JSON HTTP请求与响应_Golang JSON HTTP请求响应实践详解的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                 
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                             
                                
                                 收藏
收藏
                                                                            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号