Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Golang如何实现简单的JSON API服务_创想鸟

Golang如何实现简单的JSON API服务

答案:使用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服务

用Golang实现一个简单的JSON API服务并不复杂,核心是使用标准库中的 net/http 和 encoding/json。下面是一个完整的示例,展示如何创建一个返回JSON数据的HTTP服务。

1. 定义数据结构和路由处理函数

先定义一个结构体来表示要返回的数据,并编写处理请求的函数:

package main

import ("encoding/json""net/http")

type User struct {ID int json:"id"Name string json:"name"Email string json:"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:{"id":1,"name":"Alice","email":"alice@example.com"}访问 http://localhost:8080/health,返回纯文本 OK。

也可以用 curl 测试:

curl -s http://localhost:8080/user | python -m json.tool

4. 处理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 Usererr := json.NewDecoder(r.Body).Decode(&user)if err != nil {    http.Error(w, "Invalid JSON", http.StatusBadRequest)    return}// 模拟保存成功,返回带ID的结果user.ID = 100w.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服务的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1409793.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
Go项目布局:结构化与最佳实践指南
上一篇 2025年12月16日 02:46:50
Golang goroutine堆栈分析与调试实践
下一篇 2025年12月16日 02:47:01

相关推荐

发表回复

登录后才能评论
关注微信