简介
路由模块,封装 Gin 路由注册和请求上下文处理。提供 Handle() 函数用于注册路由、Ctx 结构体统一封装请求参数、执行时间和错误信息,以及便捷的响应方法如 JSON() / JSONWithCode() / ArgJson()。内部暴露 GinRouter 以支持直接使用 Gin API 进行路由注册。
导入
go
import "github.com/wallace5303/ee-go/ehttp/router"注意:导入路径为
ehttp/router,业务代码中通常使用别名引用:
go
import (
eRouter "github.com/wallace5303/ee-go/ehttp/router"
)API
Handle(httpMethod, path, handler)
说明:注册路由规则。内部将 HandlerFunc 转换为 Gin 处理函数,自动解析请求体 JSON 参数到 Ctx.Args,记录执行时间,并在 defer 中捕获 panic 和打印访问日志。
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| httpMethod | string | 是 | HTTP 方法,例如 "GET"、"POST"、"PUT"、"DELETE" |
| path | string | 是 | 路由路径,例如 "GET" 对应 "/api/hello" |
| handler | HandlerFunc | 是 | 路由处理函数,签名为 func(*Ctx) |
返回值:无
示例:
go
import (
eRouter "github.com/wallace5303/ee-go/ehttp/router"
"electron-egg/api"
)
func Api() {
eRouter.Handle("GET", "/api/hello", api.Hello)
eRouter.Handle("GET", "/api/exit", api.Exit)
eRouter.Handle("GET", "/api/getValue", api.GetValue)
eRouter.Handle("POST", "/api/setValue", api.SetValue)
}HandlerFunc
说明:路由处理函数类型定义。
go
type HandlerFunc func(*Ctx)示例:
go
func Hello(c *router.Ctx) {
ret := ehelper.GetJson()
defer c.JSON(ret)
ret.Data = "hello electron-egg"
}Ctx
说明:路由请求上下文,封装 Gin 上下文、请求参数、执行时间和错误信息。
| 字段 | 类型 | 说明 |
|---|---|---|
| GinCtx | *gin.Context | Gin 原生请求上下文,可直接调用 Gin API |
| Err | any | 请求处理过程中捕获的 panic 错误 |
| Timed | int64 | 请求执行时间(毫秒),由 Handle() 内部自动计算 |
| Args | map[string]any | 请求体 JSON 参数,由 Handle() 通过 ShouldBindJSON 自动解析;解析失败时为 nil |
Ctx.JSON(data)
说明:返回 JSON 格式响应数据,HTTP 状态码为 200。
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| data | any | 是 | 响应数据,通常为 *ehelper.ResultJson 结构体 |
返回值:无
示例:
go
func Hello(c *router.Ctx) {
ret := ehelper.GetJson()
ret.Data = "hello"
c.JSON(ret)
}参见:ehelper.GetJson()
Ctx.JSONWithCode(code, data)
说明:返回 JSON 格式响应数据,使用指定的 HTTP 状态码。
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| code | int | 是 | HTTP 状态码,例如 http.StatusOK(200)、http.StatusBadRequest(400) |
| data | any | 是 | 响应数据 |
返回值:无
示例:
go
func BadRequest(c *router.Ctx) {
ret := ehelper.GetJson()
ret.Code = -1
ret.Msg = "参数错误"
c.JSONWithCode(http.StatusBadRequest, ret)
}参见:ehelper.GetJson()
Ctx.ArgJson()
说明:获取请求体 JSON 参数。参数存在且解析成功时,返回参数 map 和 true;参数为空或解析失败时,返回空 map 和 false,并在返回的 ResultJson 中标记错误。
参数:无(使用已在 Ctx.Args 中解析的参数)
返回值:
| 返回值 | 类型 | 说明 |
|---|---|---|
| arg | map[string]any | 请求参数 map;解析失败时为 nil |
| ok | bool | true 表示解析成功,false 表示请求体为空或解析失败 |
示例:
go
func SetValue(c *router.Ctx) {
ret := ehelper.GetJson()
defer c.JSON(ret)
arg, ok := c.ArgJson()
if !ok {
ret.Code = -1
ret.Msg = "请求参数解析失败"
return
}
keyName := arg["key"].(string)
value := arg["value"]
// 业务逻辑...
}GinRouter
说明:Gin 原生引擎实例,暴露给业务代码以支持直接使用 Gin API 进行路由注册(如 Gin 中间件、路由分组等)。
var GinRouter *gin.Engine
示例:
go
import (
eRouter "github.com/wallace5303/ee-go/ehttp/router"
)
func Api() {
// 直接使用 Gin 注册路由
eRouter.GinRouter.GET("/api/info", api.Info)
}参见:gin.Engine
