答案是使用net/http包结合json.NewDecoder和json.NewEncoder处理JSON请求与响应。首先定义可导出的结构体并添加json标签,如User和Response;在Handler中通过json.NewDecoder(r.Body).Decode(&user)解析POST或PUT请求的JSON数据,并校验请求方法与格式;处理完成后,设置Header的Content-Type为application/json,使用json.NewEncoder(w).Encode返回结构化响应。完整示例如创建用户接口,启动HTTP服务监听8080端口,实现JSON数据的解析与返回。

在Go语言中,使用
net/http
包处理JSON接口数据非常常见,尤其是在构建RESTful API时。核心在于正确解析客户端发送的JSON请求体,并以JSON格式返回响应。下面介绍如何实现请求解析和响应返回。
解析JSON请求
当客户端通过POST或PUT请求发送JSON数据时,服务端需要读取请求体并将其反序列化为Go结构体。
使用
json.Unmarshal
可以将JSON数据映射到结构体。注意要确保结构体字段可导出(大写开头),并添加
json
标签以便正确匹配字段。
示例:
定义一个用户结构体:
立即学习“go语言免费学习笔记(深入)”;
type User struct { Name string `json:"name"` Email string `json:"email"`}
在Handler中解析JSON:
func createUser(w http.ResponseWriter, r *http.Request) { var user User // 判断请求方法 if r.Method != "POST" { http.Error(w, "只支持POST方法", http.StatusMethodNotAllowed) return } // 解析JSON请求体 err := json.NewDecoder(r.Body).Decode(&user) if err != nil { http.Error(w, "无法解析JSON", http.StatusBadRequest) return } // 处理数据(例如保存到数据库) fmt.Printf("收到用户: %+vn", user) // 返回成功响应 w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(map[string]string{"status": "success", "message": "用户创建成功"})}
返回JSON响应
向客户端返回JSON数据时,需设置响应头
Content-Type: application/json
,然后使用
json.NewEncoder
将数据编码并写入响应流。
常见做法是定义统一的响应结构:
type Response struct { Status string `json:"status"` Message string `json:"message,omitempty"` Data interface{} `json:"data,omitempty"`}
使用示例:
func getUser(w http.ResponseWriter, r *http.Request) { user := User{Name: "张三", Email: "zhangsan@example.com"} w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(Response{ Status: "success", Message: "获取成功", Data: user, })}
完整服务示例
以下是一个简单的HTTP服务,包含JSON请求处理和响应返回:
package mainimport ( "encoding/json" "log" "net/http")type User struct { Name string `json:"name"` Email string `json:"email"`}type Response struct { Status string `json:"status"` Message string `json:"message,omitempty"` Data interface{} `json:"data,omitempty"`}func createUser(w http.ResponseWriter, r *http.Request) { if r.Method != "POST" { http.Error(w, "不支持的方法", http.StatusMethodNotAllowed) return } var user User if err := json.NewDecoder(r.Body).Decode(&user); err != nil { http.Error(w, "JSON格式错误", http.StatusBadRequest) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(Response{ Status: "success", Message: "用户已创建", Data: user, })}func main() { http.HandleFunc("/user", createUser) log.Println("服务器启动在 :8080") log.Fatal(http.ListenAndServe(":8080", nil))}
基本上就这些。只要掌握
json.NewDecoder(r.Body).Decode
和
json.NewEncoder(w).Encode
的使用,就能高效处理大多数JSON接口场景。注意错误处理和Content-Type设置,避免前端解析失败。
以上就是Golang使用net/http处理JSON接口数据的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1404499.html
微信扫一扫
支付宝扫一扫