答案:使用Golang标准库net/http和encoding/json可快速构建JSON API服务。定义User结构体并用json标签指定字段名,通过http.HandleFunc注册/user和/health路由,分别返回JSON数据和健康检查响应。在处理函数中设置Content-Type为application/json,利用json.NewEncoder将结构体编码为JSON输出。支持GET请求获取用户信息,也可扩展POST请求解析JSON输入,使用json.NewDecoder解码请求体并返回创建结果。启动服务监听8080端口,通过curl或浏览器测试接口正常返回数据。

用Golang实现一个简单的JSON API服务并不复杂,核心是使用标准库中的 net/http 和 encoding/json。下面是一个完整的示例,展示如何创建一个返回JSON数据的HTTP服务。
1. 定义数据结构和路由处理函数
先定义一个结构体来表示要返回的数据,并编写处理请求的函数:
package mainimport ( "encoding/json" "net/http" )
type User struct { ID int
json:"id"Name stringjson:"name"Email stringjson:"email"}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") json.NewEncoder(w).Encode(user)}
说明:
- 使用 json: 标签控制字段在JSON中的名称。
- 设置响应头为 application/json,确保客户端正确解析。
- 使用 json.NewEncoder(w).Encode() 直接将结构体写入响应流。
2. 启动HTTP服务器并注册路由
在 main 函数中设置路由并启动服务:
立即学习“go语言免费学习笔记(深入)”;
func main() {
http.HandleFunc("/user", getUser)
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
})
println("Server is running on :8080")
http.ListenAndServe(":8080", nil)}
说明:
- 使用 http.HandleFunc 注册路径与处理函数的映射。
- 添加一个简单的健康检查接口 /health,用于测试服务是否正常。
- 调用 ListenAndServe 启动服务器,默认监听本地8080端口。
3. 测试API
运行程序后,打开终端或浏览器测试:
- 访问 http://localhost:8080/user,会返回JSON:
- 访问 http://localhost:8080/health,返回纯文本 OK。
也可以用 curl 测试:
curl -s http://localhost:8080/user | python -m json.tool4. 处理POST请求(可选扩展)
如果需要接收JSON输入,可以这样处理:
func createUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var user User
err := json.NewDecoder(r.Body).Decode(&user)
if err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// 模拟保存成功,返回带ID的结果
user.ID = 100
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(user)}
然后在 main 中注册:
http.HandleFunc("/user", createUser)(注意区分GET/POST)
基本上就这些。Golang的标准库足够应付大多数简单API场景,无需引入框架也能快速搭建稳定服务。关键点是设置正确的Content-Type、使用结构体标签、合理处理错误。后续可扩展日志、中间件、路由分组等功能。










