跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

Golang如何处理JSON HTTP请求与响应_Golang JSON HTTP请求响应实践详解

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: %+v\n", user) }
关键点: php版微信js-sdk支付接口类 php版微信js-sdk支付接口类 下载
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 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校验和资源释放。

相关文章