Go构建RESTful JSON接口的核心是net/http包配合结构体序列化,需定义带json标签的导出字段结构体、用json.Decode解析请求体、json.Encode生成响应、正确设置Content-Type头及HTTP状态码。

用 Go 构建 RESTful 接口处理 JSON 很直接,核心是 net/http 包配合结构体序列化,无需额外框架也能写出清晰、健壮的 API。
Go 通过结构体字段标签(如 json:"name")控制 JSON 的序列化与反序列化。注意大小写:只有首字母大写的字段才能被外部包访问,否则 json.Marshal 会忽略它。
例如接收用户注册请求:
type UserRequest struct {
Name string `json:"name"`
Email string `json:"email"`
Age int `json:"age"`
}响应时可定义独立结构体,避免暴露敏感字段或内部实现:
立即学习“go语言免费学习笔记(深入)”;
type UserResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
}在 HTTP 处理函数中,调用 json.NewDecoder(r.Body).Decode(&v) 将请求体解码为结构体。务必检查错误,并提前设置请求头 Content-Type: application/json,否则解码可能静默失败。
常见做法:
r.Method 是否为 POST 或 PUT
r.Header.Get("Content-Type") 粗略校验(可选)json.Decode,出错时返回 400 Bad Request
defer r.Body.Close()(虽然 Decode 读完会自动关闭,但显式写上更稳妥)用 json.NewEncoder(w).Encode(v) 直接写入响应体,比 json.Marshal + w.Write 更简洁且自动处理流式编码。别忘了设置响应头:
w.Header().Set("Content-Type", "application/json; charset=utf-8")成功时常用 200 OK 或 201 Created;出错时设对应状态码,比如:
w.WriteHeader(http.StatusBadRequest) —— 参数无效w.WriteHeader(http.StatusNotFound) —— 资源不存在w.WriteHeader(http.StatusInternalServerError) —— 服务端错误重复写 json.Decode/Encode 和状态码逻辑容易出错。可以封装两个小函数:
func parseJSON(r *http.Request, v interface{}) error {
return json.NewDecoder(r.Body).Decode(v)
}
func writeJSON(w http.ResponseWriter, status int, v interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(status)
json.NewEncoder(w).Encode(v)
}使用时就变成:
var req UserRequest
if err := parseJSON(r, &req); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON"})
return
}
writeJSON(w, http.StatusOK, UserResponse{ID: 123, Name: req.Name, Email: req.Email})不复杂但容易忽略细节,把结构体、解码、响应头、状态码这四点理清楚,RESTful JSON 接口就稳了。
以上就是如何使用Golang构建RESTful接口_处理JSON请求和响应的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号