gateway/README.md

93 lines
2.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# @go/gateway (高性能动态网关)
基于 `@go/service` 实现的微服务 API 网关。专注于作为“配置下发搬运工”,将繁重的路由转发交由底层 `service` 核心无锁处理。
---
## 🚀 快速开始 (1分钟)
### 1. 安装
```bash
go get apigo.cc/go/gateway
```
### 2. 运行 (本地配置模式)
创建 `env.yml`
```yaml
service:
Listen: ":80,http"
Proxies:
"*":
- Path: "/api/*"
ToApp: "my-backend-service" # 转发至服务发现
ToPath: "/v1/*"
```
启动:
```bash
go run . start
```
---
## 📂 核心配置 (env.yml)
网关完全继承了 `service` 的配置能力,详细配置请参考:[https://apigo.cc/go/service](https://apigo.cc/go/service)
```yaml
gateway:
Redis: "127.0.0.1:6379" # (可选) 动态配置中心
Prefix: "gateway" # 键名前缀
service:
App: "gateway"
Listen: ":80,http|:443" # 支持多端口、SSL
Register: "127.0.0.1:6379" # 服务发现中心
```
---
## 🔄 动态路由管理 (Redis)
网关自动扫描 `gateway:host:*` 格式的键,无需手动维护索引。
### A. 设置路由 (HSET)
```bash
# 配置域名 gw.test 的代理规则
HSET gateway:host:gw.test proxies '[{"Path":"/api/*","ToApp":"user-svc","ToPath":"/v1/*"}]'
# 配置域名 gw.test 的重写规则
HSET gateway:host:gw.test rewrites '[{"Path":"^/old/(.*)$","ToPath":"/new/$1"}]'
# 配置域名 gw.test 的静态目录
HSET gateway:host:gw.test statics '{"/ui":"/var/www/html"}'
```
### B. 秒级推送到全集群 (PUBLISH)
```bash
# 发布域名字符串即可触发该域名的局部热更新
PUBLISH gateway:channel "gw.test"
```
---
## 🛠 命令行操作 (CLI)
```bash
./gateway start # 后台启动
./gateway status # 查看状态(包含:监听地址、动态域名数、日志队列等)
./gateway reload # 重载本地 YAML 并全量刷入 Redis 配置
./gateway stop # 优雅停止
```
---
## 📝 路由匹配速查
| 模式 | 示例 (Path) | 说明 |
| :--- | :--- | :--- |
| **精确** | `/login` | 字符串完全一致 |
| **通配** | `/api/*` | **必须带 `/*` 结尾**,高性能前缀匹配 |
| **正则** | `^/user/(.*)$`| 包含 `(` 即视为正则,支持捕获组 |
*Host 匹配顺序:`精确域名:端口` > `纯域名` > `纯端口` > `*`。*