feat: init gateway v1.0.0, AI-First example-driven documentation (by AI)

This commit is contained in:
AI Engineer 2026-05-13 00:49:29 +08:00
parent 0984b688be
commit 6fd0e40d3f
3 changed files with 102 additions and 72 deletions

136
README.md
View File

@ -1,79 +1,73 @@
# @go/gateway # @go/gateway (高性能动态网关)
基于 `@go/service` 和 Redis 的高性能、事件驱动的动态 API 网关 基于 `@go/service` 实现的微服务 API 网关。专注于作为“配置下发搬运工”,将繁重的路由转发交由底层 `service` 核心无锁处理
`gateway` 专注于充当配置下发的搬运工,将路由匹配、转发等所有繁重工作剥离给底层的 `service` 核心。支持通过 Redis 进行 0 延迟、0 丢包的路由级全量/局部热更新。 详细路由语法与基础服务配置请参考:[https://apigo.cc/go/service](https://apigo.cc/go/service)
## 功能特性 ---
- **极致性能**:基于 `service` 包的 Copy-on-Write (写时复制) 原语,无锁构建,转发阶段无锁等待。 ## 1. 基础配置 (env.yml)
- **事件驱动热更新**:摒弃轮询,监听 Redis Pub/Sub精准下发变更配置旧连接不受影响。
- **服务发现原生集成**:与 `@go/discover` 无缝集成,支持基于服务名的直连与负载均衡。
- **生命周期接管**:由 `@go/starter` 接管,支持通过 `kill -SIGHUP` 触发本地全量重新同步。
## 配置模型 (Redis Hash)
Gateway 将配置存储在 Redis 的 Hash 结构中,并按照 **Host (域名)** 进行字段隔离,提升拉取效率和管理粒度。
- **`gateway:proxies`** 代理规则
- **`gateway:rewrites`** 重写规则
- **`gateway:statics`** 静态目录服务
### 结构示例
假设配置的 Host 为 `api.example.com`:
```json
// HSET gateway:proxies "api.example.com"
[
{ "Path": "^/user/(.*)$", "AuthLevel": 0, "ToApp": "user-service", "ToPath": "/$1" },
{ "Path": "/direct", "AuthLevel": 0, "ToApp": "http://10.0.0.1:8080", "ToPath": "/hello" }
]
// HSET gateway:rewrites "api.example.com"
[
{ "Path": "^/old-api/(.*)$", "ToPath": "/api/$1" }
]
// HSET gateway:statics "www.example.com"
{
"/ui": "/var/www/html"
}
```
## 动态热更新 API (Pub/Sub)
无需重启进程,向 Redis 的 `gateway:channel` 频道发布 JSON 消息,网关会在收到消息后仅拉取变化的那一部分(局部全量更新):
```json
{
"action": "update",
"type": "proxy", // 可选: "proxy", "rewrite", "static"
"host": "api.example.com"
}
```
## 启动与管理
```bash
# 以后台进程启动
./gateway start
# 查看服务状态 (通过 IPC)
./gateway status
# 平滑重启 / 重载兜底
./gateway restart
./gateway reload # 触发底层 service 的 OnReload全量同步 Redis
```
## 环境变量配置
支持通过环境变量或 `env.yml` 覆盖。
```yaml ```yaml
gateway: gateway:
Redis: "127.0.0.1:6379" Redis: "127.0.0.1:6379" # 配置中心 Redis
Prefix: "gateway" Prefix: "gateway" # 键名前缀 (默认为 gateway)
Channel: "gateway:channel"
service:
Listen: ":80,http" # 监听端口
Register: "127.0.0.1:6379" # 服务发现注册中心
``` ```
---
## 2. 动态路由管理 (Redis 示例)
网关以 **Host (域名)** 为单元管理配置,通过向频道发送“域名字符串”触发该域名的局部热更新。
### A. 配置存储 (HSET)
```bash
# 1. 添加 Host 到索引集 (必须)
SADD gateway:hosts "api.example.com"
# 2. 设置代理/重写/静态规则 (JSON 格式)
HSET gateway:host:api.example.com \
proxies '[
{"Path": "/user/*", "ToApp": "user-service", "ToPath": "/v1/*"},
{"Path": "/legacy", "ToApp": "http://10.0.0.1:8080", "ToPath": "/old"}
]' \
rewrites '[
{"Path": "^/api/([0-9]+)$", "ToPath": "/v2/api?id=$1"}
]' \
statics '{
"/ui": "/var/www/html"
}'
```
### B. 发布更新 (PUBLISH)
```bash
# 运维仅需发布一条域名消息,网关秒级无损更新
PUBLISH gateway:channel "api.example.com"
```
---
## 3. 命令行操作 (CLI)
```bash
./gateway start # 后台启动
./gateway status # 查看各域名健康状态与 IPC 信息
./gateway reload # 重载本地 YAML 配置并全量刷入 Redis 配置
./gateway stop # 优雅停止
```
## 4. 路由匹配速查
| 匹配模式 | 示例路径 (Path) | 说明 |
| :--- | :--- | :--- |
| **精确匹配** | `/login` | 必须完全一致 |
| **高性能前缀** | `/api/*` | **必须带 `/*` 结尾**,自动剥离前缀转发 |
| **正则匹配** | `^/user/(.*)$` | 包含 `(` 即视为正则,支持 `$1` 替换 |
---
*更多高级特性如 SSL、负载均衡超时、自动探测应用名等请查阅 [service 文档](https://apigo.cc/go/service)。*

View File

@ -35,6 +35,9 @@ func TestGateway(t *testing.T) {
service.Host("*").GET("/hello", func(req *service.Request) string { service.Host("*").GET("/hello", func(req *service.Request) string {
return "hello from backend, path: " + req.RequestURI return "hello from backend, path: " + req.RequestURI
}) })
service.Host("*").GET("/hello/world", func(req *service.Request) string {
return "hello from backend, path: " + req.RequestURI
})
asBackend := service.AsyncStart() asBackend := service.AsyncStart()
defer asBackend.Stop() defer asBackend.Stop()
@ -48,6 +51,7 @@ func TestGateway(t *testing.T) {
proxyRules := []service.ProxyRule{ proxyRules := []service.ProxyRule{
{Path: "^/api/(.*)$", ToApp: "test-backend", ToPath: "/$1"}, {Path: "^/api/(.*)$", ToApp: "test-backend", ToPath: "/$1"},
{Path: "/direct", ToApp: "test-backend", ToPath: "/hello"}, {Path: "/direct", ToApp: "test-backend", ToPath: "/hello"},
{Path: "/v2/*", ToApp: "test-backend", ToPath: "/hello/*"},
} }
rewriteRules := []service.RewriteRule{ rewriteRules := []service.RewriteRule{
{Path: "^/old-api/(.*)$", ToPath: "/api/$1"}, {Path: "^/old-api/(.*)$", ToPath: "/api/$1"},
@ -130,6 +134,22 @@ func TestGateway(t *testing.T) {
t.Fatalf("Proxy regexp failed, got: %s", body) t.Fatalf("Proxy regexp failed, got: %s", body)
} }
// ============================================
// 测试 2.1: 极速通配符前缀匹配 (Discover)
// ============================================
req, _ = gohttp.NewRequest("GET", "http://127.0.0.1:"+gwPort+"/v2/world?x=2", nil)
req.Host = "gw.test"
res, err = client.Do(req)
body = ""
if err == nil && res != nil {
b, _ := io.ReadAll(res.Body)
res.Body.Close()
body = string(b)
}
if err != nil || !strings.Contains(body, "hello from backend, path: /hello/world?x=2") {
t.Fatalf("Proxy wildcard failed, got: %s", body)
}
// ============================================ // ============================================
// 测试 3: Rewrite 后再 Proxy // 测试 3: Rewrite 后再 Proxy
// ============================================ // ============================================

18
main.go
View File

@ -12,7 +12,23 @@ func main() {
_ = config.Load(&GatewayConf, "gateway") _ = config.Load(&GatewayConf, "gateway")
// 2. 初始化 Starter 信息 // 2. 初始化 Starter 信息
starter.SetAppInfo("gateway", "2.0.0") starter.SetAppInfo("gateway", "1.0.0")
starter.SetUsage(`High-performance API gateway based on apigo.cc/go/service.
Full Guide: https://apigo.cc/go/service
Example Config (env.yml):
gateway:
Redis: "127.0.0.1:6379" # Configuration Center
service:
Listen: ":80,http" # HTTP Port
Dynamic Route Update (via redis-cli):
PUBLISH gateway:channel "api.example.com"
Matching Logic:
- Exact: "/login" (Literal string)
- Prefix: "/api/*" (Matches start, requires suffix "/*")
- Regex: "^/v1/(.*)$" (Matches pattern if "(" is present)`)
// 3. 注册 Gateway 服务 // 3. 注册 Gateway 服务
// GatewayApp 自身实现了 starter.Service 和 starter.Reloader 接口 // GatewayApp 自身实现了 starter.Service 和 starter.Reloader 接口