答案:使用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服务。
先定义一个结构体来表示要返回的数据,并编写处理请求的函数:
package main
<p>import (
"encoding/json"
"net/http"
)</p><p>type User struct {
ID   int    <code>json:"id"</code>
Name string <code>json:"name"</code>
Email string <code>json:"email"</code>
}</p><p>func getUser(w http.ResponseWriter, r *http.Request) {
user := User{
ID:    1,
Name:  "Alice",
Email: "alice@example.com",
}</p><pre class='brush:php;toolbar:false;'>w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)}
说明:
- 使用 json: 标签控制字段在JSON中的名称。
- 设置响应头为 application/json,确保客户端正确解析。
- 使用 json.NewEncoder(w).Encode() 直接将结构体写入响应流。
在 main 函数中设置路由并启动服务:
立即学习“go语言免费学习笔记(深入)”;
func main() {
    http.HandleFunc("/user", getUser)
<pre class='brush:php;toolbar:false;'>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端口。
运行程序后,打开终端或浏览器测试:
 
                        Easily find JSON paths within JSON objects using our intuitive Json Path Finder
 30
30
                             
                    也可以用 curl 测试:
curl -s http://localhost:8080/user | python -m json.tool如果需要接收JSON输入,可以这样处理:
func createUser(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
        http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
        return
    }
<pre class='brush:php;toolbar:false;'>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、使用结构体标签、合理处理错误。后续可扩展日志、中间件、路由分组等功能。
以上就是Golang如何实现简单的JSON API服务的详细内容,更多请关注php中文网其它相关文章!
 
                        
                        每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
 
                Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号