Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
503d0904d5 | ||
|
|
e6c6f68a3a |
@@ -9,11 +9,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Fun struct {
|
type Fun struct {
|
||||||
methods map[string]methodInfo
|
methods map[string]methodInfo
|
||||||
routes map[string]RouteHandler // 自定义路由:"GET /path" → 处理器
|
routes map[string]RouteHandler // 自定义路由:"GET /path" → 处理器(精确匹配)
|
||||||
boxes *sync.Map // 依赖容器:reflect.Type → reflect.Value
|
wildcardRoutes map[string][]wildcardRoute
|
||||||
guards []*any // 全局 Guard
|
boxes *sync.Map // 依赖容器:reflect.Type → reflect.Value
|
||||||
serviceGuards map[string][]*any // 服务级 Guard,按服务名
|
guards []*any // 全局 Guard
|
||||||
|
serviceGuards map[string][]*any // 服务级 Guard,按服务名
|
||||||
|
}
|
||||||
|
|
||||||
|
// wildcardRoute 通配符路由(BindRoute path 以 "/*" 结尾注册):
|
||||||
|
// prefix 如 "/image",匹配 prefix 与 prefix 下任意子路径
|
||||||
|
type wildcardRoute struct {
|
||||||
|
prefix string
|
||||||
|
handler RouteHandler
|
||||||
}
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@@ -33,10 +41,11 @@ type methodInfo struct {
|
|||||||
|
|
||||||
func New() *Fun {
|
func New() *Fun {
|
||||||
f := &Fun{
|
f := &Fun{
|
||||||
methods: map[string]methodInfo{},
|
methods: map[string]methodInfo{},
|
||||||
routes: map[string]RouteHandler{},
|
routes: map[string]RouteHandler{},
|
||||||
boxes: &sync.Map{},
|
wildcardRoutes: map[string][]wildcardRoute{},
|
||||||
serviceGuards: map[string][]*any{},
|
boxes: &sync.Map{},
|
||||||
|
serviceGuards: map[string][]*any{},
|
||||||
}
|
}
|
||||||
if fun == nil {
|
if fun == nil {
|
||||||
fun = f
|
fun = f
|
||||||
|
|||||||
@@ -7,19 +7,27 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
)
|
)
|
||||||
|
|
||||||
// handle 处理 HTTP 请求:先匹配自定义路由(BindRoute),未命中走 /cell RPC
|
// handle 处理 HTTP 请求:先匹配自定义路由(BindRoute 精确/通配),未命中走 /cell RPC
|
||||||
func (f *Fun) handle(fastCtx *fasthttp.RequestCtx) {
|
func (f *Fun) handle(fastCtx *fasthttp.RequestCtx) {
|
||||||
ctx := &Ctx{RequestCtx: fastCtx}
|
ctx := &Ctx{RequestCtx: fastCtx}
|
||||||
defer f.handlePanic(ctx)
|
defer f.handlePanic(ctx)
|
||||||
|
|
||||||
if handler, ok := f.routes[string(fastCtx.Method())+" "+string(fastCtx.Path())]; ok {
|
method, path := string(fastCtx.Method()), string(fastCtx.Path())
|
||||||
f.handleRoute(fastCtx, handler)
|
if handler, ok := f.routes[method+" "+path]; ok {
|
||||||
|
f.handleRoute(fastCtx, handler, "")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
for _, r := range f.wildcardRoutes[method] {
|
||||||
|
if path == r.prefix || strings.HasPrefix(path, r.prefix+"/") {
|
||||||
|
f.handleRoute(fastCtx, r.handler, strings.TrimPrefix(path, r.prefix+"/"))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
if ctx.path() != "/cell" {
|
if ctx.path() != "/cell" {
|
||||||
ctx.setStatusCode(fasthttp.StatusNotFound)
|
ctx.setStatusCode(fasthttp.StatusNotFound)
|
||||||
|
|||||||
@@ -16,10 +16,12 @@ type RouteHandler func(ctx *RouteCtx) error
|
|||||||
|
|
||||||
// RouteCtx 自定义路由上下文:Data 合并了 URL 查询参数与 POST 表单参数(表单优先),
|
// RouteCtx 自定义路由上下文:Data 合并了 URL 查询参数与 POST 表单参数(表单优先),
|
||||||
// 支付回调等第三方以 form-urlencoded 回调的场景可直接 Param 取值。
|
// 支付回调等第三方以 form-urlencoded 回调的场景可直接 Param 取值。
|
||||||
|
// Wildcard 为通配符路由(/prefix/*)匹配到的剩余路径(不含前导 "/")。
|
||||||
// 独立于服务内嵌的 Ctx:后者辅助方法刻意全小写以防混入 RPC 方法集,路由不复用该类型。
|
// 独立于服务内嵌的 Ctx:后者辅助方法刻意全小写以防混入 RPC 方法集,路由不复用该类型。
|
||||||
type RouteCtx struct {
|
type RouteCtx struct {
|
||||||
RequestCtx *fasthttp.RequestCtx
|
RequestCtx *fasthttp.RequestCtx
|
||||||
Data map[string]string
|
Data map[string]string
|
||||||
|
Wildcard string
|
||||||
}
|
}
|
||||||
|
|
||||||
// Param 取查询/表单参数,不存在返回空串
|
// Param 取查询/表单参数,不存在返回空串
|
||||||
@@ -27,10 +29,12 @@ func (c *RouteCtx) Param(name string) string {
|
|||||||
return c.Data[name]
|
return c.Data[name]
|
||||||
}
|
}
|
||||||
|
|
||||||
// BindRoute 注册自定义路由(方法大小写不敏感 + 精确路径匹配),用于 GET 直链、
|
// BindRoute 注册自定义路由(方法大小写不敏感;path 精确匹配,或以 "/*" 结尾做前缀通配),
|
||||||
// 健康检查、支付回调等无法走 POST /cell RPC 的场景。
|
// 用于 GET 直链、健康检查、支付回调等无法走 POST /cell RPC 的场景。
|
||||||
//
|
//
|
||||||
// - path 必须以 "/" 开头;/cell 为 RPC 保留路径,不可注册
|
// - path 必须以 "/" 开头;/cell 为 RPC 保留路径,不可注册
|
||||||
|
// - 通配符形式如 "/image/*":匹配 "/image/a/b.png" 等任意子路径,
|
||||||
|
// 匹配到的剩余路径(去掉前导 "/",如 "a/b.png")经 RouteCtx.Wildcard 取出
|
||||||
// - 同一 方法+路径 重复注册直接 panic
|
// - 同一 方法+路径 重复注册直接 panic
|
||||||
// - 与 BindService 一致,需在 Start 前完成注册(启动阶段单线程)
|
// - 与 BindService 一致,需在 Start 前完成注册(启动阶段单线程)
|
||||||
func (f *Fun) BindRoute(method, path string, handler RouteHandler) {
|
func (f *Fun) BindRoute(method, path string, handler RouteHandler) {
|
||||||
@@ -44,9 +48,21 @@ func (f *Fun) BindRoute(method, path string, handler RouteHandler) {
|
|||||||
if !strings.HasPrefix(path, "/") {
|
if !strings.HasPrefix(path, "/") {
|
||||||
panic(fmt.Sprintf("fun: BindRoute path %q must start with '/'", path))
|
panic(fmt.Sprintf("fun: BindRoute path %q must start with '/'", path))
|
||||||
}
|
}
|
||||||
if path == "/cell" {
|
if path == "/cell" || path == "/cell/*" {
|
||||||
panic("fun: /cell is reserved for RPC")
|
panic("fun: /cell is reserved for RPC")
|
||||||
}
|
}
|
||||||
|
if prefix, ok := strings.CutSuffix(path, "/*"); ok {
|
||||||
|
if prefix == "" || strings.HasSuffix(prefix, "/") {
|
||||||
|
panic(fmt.Sprintf("fun: BindRoute wildcard path %q invalid (no trailing '/' allowed before /*)", path))
|
||||||
|
}
|
||||||
|
for _, r := range f.wildcardRoutes[method] {
|
||||||
|
if r.prefix == prefix {
|
||||||
|
panic(fmt.Sprintf("fun: route %s %s/* already bound", method, prefix))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
f.wildcardRoutes[method] = append(f.wildcardRoutes[method], wildcardRoute{prefix: prefix, handler: handler})
|
||||||
|
return
|
||||||
|
}
|
||||||
key := method + " " + path
|
key := method + " " + path
|
||||||
if _, exists := f.routes[key]; exists {
|
if _, exists := f.routes[key]; exists {
|
||||||
panic(fmt.Sprintf("fun: route %s already bound", key))
|
panic(fmt.Sprintf("fun: route %s already bound", key))
|
||||||
@@ -55,8 +71,8 @@ func (f *Fun) BindRoute(method, path string, handler RouteHandler) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// handleRoute 执行自定义路由:合并查询与表单参数(application/x-www-form-urlencoded),
|
// handleRoute 执行自定义路由:合并查询与表单参数(application/x-www-form-urlencoded),
|
||||||
// 处理器返回 error 时按统一 Result 格式输出错误响应
|
// 处理器返回 error 时按统一 Result 格式输出错误响应;wildcard 为通配路由匹配的剩余路径
|
||||||
func (f *Fun) handleRoute(fastCtx *fasthttp.RequestCtx, handler RouteHandler) {
|
func (f *Fun) handleRoute(fastCtx *fasthttp.RequestCtx, handler RouteHandler, wildcard string) {
|
||||||
data := map[string]string{}
|
data := map[string]string{}
|
||||||
fastCtx.QueryArgs().VisitAll(func(k, v []byte) {
|
fastCtx.QueryArgs().VisitAll(func(k, v []byte) {
|
||||||
data[string(k)] = string(v)
|
data[string(k)] = string(v)
|
||||||
@@ -64,7 +80,7 @@ func (f *Fun) handleRoute(fastCtx *fasthttp.RequestCtx, handler RouteHandler) {
|
|||||||
fastCtx.PostArgs().VisitAll(func(k, v []byte) {
|
fastCtx.PostArgs().VisitAll(func(k, v []byte) {
|
||||||
data[string(k)] = string(v)
|
data[string(k)] = string(v)
|
||||||
})
|
})
|
||||||
if err := handler(&RouteCtx{RequestCtx: fastCtx, Data: data}); err != nil {
|
if err := handler(&RouteCtx{RequestCtx: fastCtx, Data: data, Wildcard: wildcard}); err != nil {
|
||||||
(&Ctx{RequestCtx: fastCtx}).sendError(err)
|
(&Ctx{RequestCtx: fastCtx}).sendError(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+27
-20
@@ -11,17 +11,22 @@ func (ctx templateTs) genClientTemplate() string {
|
|||||||
status: number;
|
status: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type resultStatus = 0 | 1 | 2 | 4 | 5;
|
||||||
|
// 0 成功;1 框架错误;2 业务错误;4 网络错误;5 超时
|
||||||
|
|
||||||
export type RequestInterceptor = (
|
export type RequestInterceptor = (
|
||||||
serviceName: string,
|
serviceName: string,
|
||||||
methodName: string,
|
methodName: string,
|
||||||
dto: any
|
state: Record<string, string>,
|
||||||
|
dto?: any
|
||||||
) => Promise<void> | void;
|
) => Promise<void> | void;
|
||||||
|
|
||||||
|
// 返回新 result 将替换原结果继续向下传递(可用于集中换 token / 错误处理)
|
||||||
export type ResponseInterceptor = (
|
export type ResponseInterceptor = (
|
||||||
serviceName: string,
|
serviceName: string,
|
||||||
methodName: string,
|
methodName: string,
|
||||||
result: result<any>
|
result: result<any>
|
||||||
) => Promise<void> | void;
|
) => Promise<result<any> | void> | result<any> | void;
|
||||||
|
|
||||||
export class Client {
|
export class Client {
|
||||||
private url: string;
|
private url: string;
|
||||||
@@ -46,26 +51,27 @@ export class Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async request<T>(serviceName: string, methodName: string, dto?: any): Promise<result<T>> {
|
async request<T>(serviceName: string, methodName: string, dto?: any): Promise<result<T>> {
|
||||||
|
const state: Record<string, string> = { ...this.state };
|
||||||
for (const i of this.requestInterceptors) {
|
for (const i of this.requestInterceptors) {
|
||||||
await i(serviceName, methodName, dto);
|
await i(serviceName, methodName, state, dto);
|
||||||
}
|
}
|
||||||
const res = await fetch(this.url + "/cell", {
|
let out: result<T>;
|
||||||
method: "POST",
|
try {
|
||||||
headers: { "Content-Type": "application/json" },
|
const res = await fetch(this.url + "/cell", {
|
||||||
body: JSON.stringify({ serviceName, methodName, data: dto, ...(Object.keys(this.state).length ? { state: this.state } : {}) }),
|
method: "POST",
|
||||||
});
|
headers: { "Content-Type": "application/json" },
|
||||||
const out = (await res.json()) as result<T>;
|
body: JSON.stringify({ serviceName, methodName, data: dto, ...(Object.keys(state).length ? { state } : {}) }),
|
||||||
const anyResult: result<any> = {
|
});
|
||||||
id: out.id,
|
out = (await res.json()) as result<T>;
|
||||||
code: out.code,
|
} catch (e: any) {
|
||||||
data: out.data,
|
out = { status: 4, msg: (e && e.message) || "网络错误" } as result<T>;
|
||||||
msg: out.msg,
|
}
|
||||||
status: out.status,
|
let cur: result<any> = out as result<any>;
|
||||||
};
|
|
||||||
for (const i of this.responseInterceptors) {
|
for (const i of this.responseInterceptors) {
|
||||||
await i(serviceName, methodName, anyResult);
|
const replaced = await i(serviceName, methodName, cur);
|
||||||
|
if (replaced) cur = replaced;
|
||||||
}
|
}
|
||||||
return out;
|
return cur as result<T>;
|
||||||
}
|
}
|
||||||
|
|
||||||
async stream<T>(
|
async stream<T>(
|
||||||
@@ -74,13 +80,14 @@ export class Client {
|
|||||||
dto: any | undefined,
|
dto: any | undefined,
|
||||||
onMessage: (data: T) => void
|
onMessage: (data: T) => void
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
const state: Record<string, string> = { ...this.state };
|
||||||
for (const i of this.requestInterceptors) {
|
for (const i of this.requestInterceptors) {
|
||||||
await i(serviceName, methodName, dto);
|
await i(serviceName, methodName, state, dto);
|
||||||
}
|
}
|
||||||
const res = await fetch(this.url + "/cell", {
|
const res = await fetch(this.url + "/cell", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "Content-Type": "application/json" },
|
headers: { "Content-Type": "application/json" },
|
||||||
body: JSON.stringify({ serviceName, methodName, data: dto, ...(Object.keys(this.state).length ? { state: this.state } : {}) }),
|
body: JSON.stringify({ serviceName, methodName, data: dto, ...(Object.keys(state).length ? { state } : {}) }),
|
||||||
});
|
});
|
||||||
if (!res.ok) return;
|
if (!res.ok) return;
|
||||||
const anyResult: result<any> = { status: 0 };
|
const anyResult: result<any> = { status: 0 };
|
||||||
|
|||||||
Reference in New Issue
Block a user