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数据,第一步是定义与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语言免费学习笔记(深入)”;
解析JSON请求体(Unmarshal)
在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: %+vn", user)}
关键点:
json.NewDecoder直接从r.Body流式读取,适合大体积数据且性能较好。 记得调用defer r.Body.Close()释放资源。 对解析错误返回400 Bad Request,内容类型错误返回415 Unsupported Media Type。
返回JSON响应(Marshal)
向客户端返回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。
完整HTTP服务示例
将上述部分整合成一个简单服务:
package mainimport ( "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请求响应实践详解的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1418642.html
微信扫一扫
支付宝扫一扫