Gin 实战 3:第一个接口
本章把临时写在 main.go 里的 /ping 拆到 Handler 和 Router 中,形成后续模块开发的基本姿势。
1. 创建 Handler
创建 internal/system/hello/handler.go:
go
package hello
import "github.com/gin-gonic/gin"
// Hello 是第一个业务风格接口。
// Handler 只处理 HTTP 入参和响应,不负责启动服务。
func Hello(c *gin.Context) {
c.JSON(200, gin.H{
// code/msg/data 是后台系统常见的统一响应结构。
// 后面的统一响应章节会把它抽成公共 response 包。
"code": "00000",
"msg": "成功",
"data": gin.H{"message": "Hello, youlai-gin"},
})
}2. 注册模块路由
创建 internal/system/hello/router.go:
go
package hello
import "github.com/gin-gonic/gin"
// RegisterRoutes 只注册 hello 模块自己的路由。
// 每个模块维护自己的路由,项目大了之后更容易查找。
func RegisterRoutes(r *gin.RouterGroup) {
r.GET("/hello", Hello)
}创建 internal/router/router.go:
go
package router
import (
"github.com/gin-gonic/gin"
"youlai-gin/internal/system/hello"
)
// Register 是全局路由入口。
// main.go 只调用 router.Register,不直接关心每个模块有哪些接口。
func Register(r *gin.Engine) {
// /api/v1 作为后端接口统一前缀,方便前端和网关统一代理。
api := r.Group("/api/v1")
// 把 hello 模块挂到 /api/v1 分组下。
hello.RegisterRoutes(api)
}3. main.go 接入路由
go
r := gin.New()
// 统一注册项目所有业务路由。
router.Register(r)启动后访问:
bash
curl http://localhost:8000/api/v1/hello返回:
json
{
"code": "00000",
"msg": "成功",
"data": {
"message": "Hello, youlai-gin"
}
}4. 常用接口调试方法
第一个接口写完后,不要只看代码,要养成“写完就调”的习惯。常用方式有四种:
浏览器
GET 接口可以直接在浏览器地址栏访问:
text
http://localhost:8000/api/v1/hello浏览器适合快速验证接口是否能访问,但不方便调试 POST、请求头和复杂参数。
curl
命令行最直接:
bash
curl http://localhost:8000/api/v1/hello如果要看响应头,可以加 -i:
bash
curl -i http://localhost:8000/api/v1/hello后面调试 POST JSON 时会经常用到:
bash
curl -X POST http://localhost:8000/api/v1/users \
-H "Content-Type: application/json" \
-d '{"username":"admin","nickname":"管理员"}'Postman / Apifox
这类图形化工具适合保存接口集合、切换环境、配置请求头和调试 JSON 请求体。后面登录认证章节需要带 Authorization 请求头,用它们会更直观。
GoLand HTTP Client
GoLand 可以直接创建 .http 文件:
http
GET http://localhost:8000/api/v1/hello点击运行即可发请求,适合把常用接口调试脚本和项目代码放在一起管理。
到这里,项目已经有了入口、配置、路由分组、第一个接口和基本调试方法。下一章接入 Swagger,让接口说明和在线调试更规范。
