简介
HTTP 服务模块,基于 Gin 框架创建和管理 HTTP 服务器。负责服务启动、CORS 跨域、Gzip 压缩、Session 管理、静态资源加载、路由分发、平台检测和端口占用检查。在 ee-go 初始化流程中,由 eboot 调用 CreateServer() 自动启动。
导入
import "github.com/wallace5303/ee-go/ehttp"常量
PlatformPC
string — "pc",Electron 桌面客户端的平台标识符。
PlatformBrowser
string — "browser",浏览器桌面客户端的平台标识符。
PlatformPhone
string — "phone",移动端客户端的平台标识符。
PlatformPad
string — "pad",平板端客户端的平台标识符。
Conf
map[string]any — HTTP 配置全局变量,由 CreateServer() 写入,存储 http 配置项(端口、网络等)。
API
CreateServer(cfg)
说明:创建并启动 HTTP 服务器。基于 Gin 框架,依次注册 CORS、Session 和 Gzip 中间件,加载调试路由(pprof)、静态资源和视图路由,检查端口占用,然后监听服务。
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| cfg | map[string]any | 是 | HTTP 配置,包含 port(float64→int)、network(bool)等字段 |
返回值:无
示例:
httpCfg := econfig.GetHttp()
if httpCfg["enable"] == true {
ehttp.CreateServer(httpCfg)
}参见:econfig.GetHttp(), erouter
GetPlatform(ctx)
说明:根据 HTTP 请求的 User-Agent 头判断当前访问平台类型。Electron 客户端返回 "pc";平板或大屏 Android 返回 "browser";手机端返回 "phone";其他浏览器返回 "browser"。
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| ctx | *gin.Context | 是 | Gin 请求上下文 |
返回值:string — 平台标识符,取值为 PlatformPC、PlatformBrowser、PlatformPhone 之一
示例:
platform := ehttp.GetPlatform(ctx)
if platform == ehttp.PlatformPC {
// 桌面端逻辑
} else if platform == ehttp.PlatformPhone {
// 移动端逻辑
}IsPortOpen(port)
说明:检查指定的 TCP 端口是否已被占用。通过 net.DialTimeout 在 1 秒内尝试连接 127.0.0.1:port。如果连接成功,则端口已开放(被占用)。
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
| port | string | 是 | 端口号字符串,例如 "7073" |
返回值:bool — true 表示端口被占用,false 表示端口可用
示例:
port := "7073"
if ehttp.IsPortOpen(port) {
fmt.Printf("端口 %s 已被占用\n", port)
} else {
fmt.Printf("端口 %s 可用\n", port)
}