3 Commits
Author SHA1 Message Date
chiyi 503d0904d5 v1.3.0: BindRoute wildcard routes (/prefix/*) with RouteCtx.Wildcard 2026-08-20 21:10:24 +08:00
chiyi e6c6f68a3a fun: upgrade TS client interceptors to fun-client parity (v1.2.0)
- request interceptor now receives the mutable per-request state map (token injection)
- response interceptor may return a replacement result (central token swap / error handling)
- fetch failures normalized to result status=4 (network error) instead of throwing
- stream requests also pass through request interceptors with state copy
2026-08-20 12:09:43 +08:00
chiyi 05af3dc825 fun: add BindRoute for custom HTTP routes (GET/POST, form-data callbacks)
- BindRoute(method, path, handler) with exact-match routing dispatched before /cell RPC
- RouteCtx merges query args and form-urlencoded POST args for callback scenarios (e.g. epay notify)
- handler returns error -> unified Result error response; nil -> full control via fasthttp.RequestCtx (plain-text 'success' replies)
- /cell reserved; duplicate/invalid registration panics at startup; all existing tests pass
2026-08-20 10:17:56 +08:00
5 changed files with 280 additions and 28 deletions
+18 -7
View File
@@ -9,10 +9,19 @@ import (
)
type Fun struct {
methods map[string]methodInfo
boxes *sync.Map // 依赖容器:reflect.Type → reflect.Value
guards []*any // 全局 Guard
serviceGuards map[string][]*any // 服务级 Guard,按服务名
methods map[string]methodInfo
routes map[string]RouteHandler // 自定义路由:"GET /path" → 处理器(精确匹配)
wildcardRoutes map[string][]wildcardRoute
boxes *sync.Map // 依赖容器:reflect.Type → reflect.Value
guards []*any // 全局 Guard
serviceGuards map[string][]*any // 服务级 Guard,按服务名
}
// wildcardRoute 通配符路由(BindRoute path 以 "/*" 结尾注册):
// prefix 如 "/image",匹配 prefix 与 prefix 下任意子路径
type wildcardRoute struct {
prefix string
handler RouteHandler
}
var (
@@ -32,9 +41,11 @@ type methodInfo struct {
func New() *Fun {
f := &Fun{
methods: map[string]methodInfo{},
boxes: &sync.Map{},
serviceGuards: map[string][]*any{},
methods: map[string]methodInfo{},
routes: map[string]RouteHandler{},
wildcardRoutes: map[string][]wildcardRoute{},
boxes: &sync.Map{},
serviceGuards: map[string][]*any{},
}
if fun == nil {
fun = f
+14 -1
View File
@@ -7,15 +7,28 @@ import (
"fmt"
"reflect"
"runtime/debug"
"strings"
"github.com/valyala/fasthttp"
)
// handle 处理 HTTP 请求
// handle 处理 HTTP 请求:先匹配自定义路由(BindRoute 精确/通配),未命中走 /cell RPC
func (f *Fun) handle(fastCtx *fasthttp.RequestCtx) {
ctx := &Ctx{RequestCtx: fastCtx}
defer f.handlePanic(ctx)
method, path := string(fastCtx.Method()), string(fastCtx.Path())
if handler, ok := f.routes[method+" "+path]; ok {
f.handleRoute(fastCtx, handler, "")
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" {
ctx.setStatusCode(fasthttp.StatusNotFound)
return
+86
View File
@@ -0,0 +1,86 @@
package fun
import (
"fmt"
"strings"
"github.com/valyala/fasthttp"
)
// RouteHandler 自定义 HTTP 路由处理器。
//
// 返回 error 时框架统一输出错误响应;返回 nil 视为已自行写回响应——
// 可直接操作 RouteCtx.RequestCtx 完全自定义状态码与内容
// (如支付回调要求的纯文本 "success" 应答)。
type RouteHandler func(ctx *RouteCtx) error
// RouteCtx 自定义路由上下文:Data 合并了 URL 查询参数与 POST 表单参数(表单优先),
// 支付回调等第三方以 form-urlencoded 回调的场景可直接 Param 取值。
// Wildcard 为通配符路由(/prefix/*)匹配到的剩余路径(不含前导 "/")。
// 独立于服务内嵌的 Ctx:后者辅助方法刻意全小写以防混入 RPC 方法集,路由不复用该类型。
type RouteCtx struct {
RequestCtx *fasthttp.RequestCtx
Data map[string]string
Wildcard string
}
// Param 取查询/表单参数,不存在返回空串
func (c *RouteCtx) Param(name string) string {
return c.Data[name]
}
// BindRoute 注册自定义路由(方法大小写不敏感;path 精确匹配,或以 "/*" 结尾做前缀通配),
// 用于 GET 直链、健康检查、支付回调等无法走 POST /cell RPC 的场景。
//
// - path 必须以 "/" 开头;/cell 为 RPC 保留路径,不可注册
// - 通配符形式如 "/image/*":匹配 "/image/a/b.png" 等任意子路径,
// 匹配到的剩余路径(去掉前导 "/",如 "a/b.png")经 RouteCtx.Wildcard 取出
// - 同一 方法+路径 重复注册直接 panic
// - 与 BindService 一致,需在 Start 前完成注册(启动阶段单线程)
func (f *Fun) BindRoute(method, path string, handler RouteHandler) {
if handler == nil {
panic("fun: BindRoute handler cannot be nil")
}
method = strings.ToUpper(strings.TrimSpace(method))
if method == "" {
panic("fun: BindRoute method cannot be empty")
}
if !strings.HasPrefix(path, "/") {
panic(fmt.Sprintf("fun: BindRoute path %q must start with '/'", path))
}
if path == "/cell" || path == "/cell/*" {
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
if _, exists := f.routes[key]; exists {
panic(fmt.Sprintf("fun: route %s already bound", key))
}
f.routes[key] = handler
}
// handleRoute 执行自定义路由:合并查询与表单参数(application/x-www-form-urlencoded),
// 处理器返回 error 时按统一 Result 格式输出错误响应;wildcard 为通配路由匹配的剩余路径
func (f *Fun) handleRoute(fastCtx *fasthttp.RequestCtx, handler RouteHandler, wildcard string) {
data := map[string]string{}
fastCtx.QueryArgs().VisitAll(func(k, v []byte) {
data[string(k)] = string(v)
})
fastCtx.PostArgs().VisitAll(func(k, v []byte) {
data[string(k)] = string(v)
})
if err := handler(&RouteCtx{RequestCtx: fastCtx, Data: data, Wildcard: wildcard}); err != nil {
(&Ctx{RequestCtx: fastCtx}).sendError(err)
}
}
+135
View File
@@ -0,0 +1,135 @@
package fun
import (
"fmt"
"net/http"
"net/url"
"strings"
"testing"
"time"
)
func startRouteServer(t *testing.T, port uint16) *Fun {
t.Helper()
f := New()
f.BindService(&TestSvc{})
// GET:查询参数 + 纯文本自定义响应
f.BindRoute("GET", "/ping", func(ctx *RouteCtx) error {
ctx.RequestCtx.SetContentType("text/plain; charset=utf-8")
ctx.RequestCtx.WriteString("pong " + ctx.Param("echo"))
return nil
})
// POST:支付回调场景,form-urlencoded 参数合并取值,成功回纯文本 success
f.BindRoute("POST", "/pay/notify", func(ctx *RouteCtx) error {
if ctx.Param("trade_status") != "TRADE_SUCCESS" {
return Error(4001, "invalid trade_status")
}
ctx.RequestCtx.SetContentType("text/plain; charset=utf-8")
ctx.RequestCtx.WriteString("success")
return nil
})
// 返回 error:应输出统一错误响应
f.BindRoute("GET", "/boom", func(ctx *RouteCtx) error {
return fmt.Errorf("kaboom")
})
go f.Start(port)
time.Sleep(300 * time.Millisecond)
return f
}
func TestBindRouteGet(t *testing.T) {
startRouteServer(t, 39101)
resp, err := http.Get("http://127.0.0.1:39101/ping?echo=hi")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d", resp.StatusCode)
}
body := make([]byte, 32)
n, _ := resp.Body.Read(body)
if got := strings.TrimSpace(string(body[:n])); got != "pong hi" {
t.Fatalf("unexpected body: %q", got)
}
}
func TestBindRoutePayNotifyForm(t *testing.T) {
startRouteServer(t, 39102)
form := url.Values{"out_trade_no": {"T123"}, "trade_status": {"TRADE_SUCCESS"}, "money": {"0.01"}}
resp, err := http.PostForm("http://127.0.0.1:39102/pay/notify", form)
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
buf := make([]byte, 64)
n, _ := resp.Body.Read(buf)
if got := strings.TrimSpace(string(buf[:n])); got != "success" {
t.Fatalf("unexpected body: %q", got)
}
// 非成功状态 → 统一错误响应
resp2, err := http.PostForm("http://127.0.0.1:39102/pay/notify",
url.Values{"trade_status": {"WAIT_BUYER_PAY"}})
if err != nil {
t.Fatal(err)
}
defer resp2.Body.Close()
buf2 := make([]byte, 256)
n2, _ := resp2.Body.Read(buf2)
if !strings.Contains(string(buf2[:n2]), "invalid trade_status") {
t.Fatalf("unexpected error body: %q", string(buf2[:n2]))
}
}
func TestBindRouteErrorAndCellUnaffected(t *testing.T) {
startRouteServer(t, 39103)
// error 路由 → 统一错误 JSON
resp, err := http.Get("http://127.0.0.1:39103/boom")
if err != nil {
t.Fatal(err)
}
defer resp.Body.Close()
buf := make([]byte, 256)
n, _ := resp.Body.Read(buf)
if !strings.Contains(string(buf[:n]), "kaboom") {
t.Fatalf("unexpected error body: %q", string(buf[:n]))
}
// 未注册路径仍 404/cell RPC 不受影响
if resp2, err := http.Get("http://127.0.0.1:39103/nope"); err != nil || resp2.StatusCode != 404 {
t.Fatalf("unregistered route should 404: %v %+v", err, resp2)
} else {
resp2.Body.Close()
}
res := postCell(t, 39103, `{"serviceName":"TestSvc","methodName":"Hello","data":{"name":"tom","age":1}}`)
if res.Status != 0 || res.Data == nil || (*res.Data).(string) != "hi tom" {
t.Fatalf("/cell broken by routes: %+v", res)
}
// 方法不匹配(GET 打 POST 路由)→ 404
if resp3, err := http.Get("http://127.0.0.1:39103/pay/notify"); err != nil || resp3.StatusCode != 404 {
t.Fatalf("method mismatch should 404: %v %+v", err, resp3)
} else {
resp3.Body.Close()
}
}
func TestBindRoutePanics(t *testing.T) {
f := New()
catch := func(fn func()) (msg string) {
defer func() { msg = fmt.Sprint(recover()) }()
fn()
return ""
}
if m := catch(func() { f.BindRoute("GET", "no-slash", func(*RouteCtx) error { return nil }) }); m == "" {
t.Fatal("path without leading / should panic")
}
if m := catch(func() { f.BindRoute("GET", "/cell", func(*RouteCtx) error { return nil }) }); m == "" {
t.Fatal("/cell reservation should panic")
}
f.BindRoute("get", "/dup", func(*RouteCtx) error { return nil })
if m := catch(func() { f.BindRoute("GET", "/dup", func(*RouteCtx) error { return nil }) }); m == "" {
t.Fatal("duplicate route should panic")
}
}
+27 -20
View File
@@ -11,17 +11,22 @@ func (ctx templateTs) genClientTemplate() string {
status: number;
};
export type resultStatus = 0 | 1 | 2 | 4 | 5;
// 0 成功;1 框架错误;2 业务错误;4 网络错误;5 超时
export type RequestInterceptor = (
serviceName: string,
methodName: string,
dto: any
state: Record<string, string>,
dto?: any
) => Promise<void> | void;
// 返回新 result 将替换原结果继续向下传递(可用于集中换 token / 错误处理)
export type ResponseInterceptor = (
serviceName: string,
methodName: string,
result: result<any>
) => Promise<void> | void;
) => Promise<result<any> | void> | result<any> | void;
export class Client {
private url: string;
@@ -46,26 +51,27 @@ export class Client {
}
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) {
await i(serviceName, methodName, dto);
await i(serviceName, methodName, state, dto);
}
const res = await fetch(this.url + "/cell", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ serviceName, methodName, data: dto, ...(Object.keys(this.state).length ? { state: this.state } : {}) }),
});
const out = (await res.json()) as result<T>;
const anyResult: result<any> = {
id: out.id,
code: out.code,
data: out.data,
msg: out.msg,
status: out.status,
};
let out: result<T>;
try {
const res = await fetch(this.url + "/cell", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ serviceName, methodName, data: dto, ...(Object.keys(state).length ? { state } : {}) }),
});
out = (await res.json()) as result<T>;
} catch (e: any) {
out = { status: 4, msg: (e && e.message) || "网络错误" } as result<T>;
}
let cur: result<any> = out as result<any>;
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>(
@@ -74,13 +80,14 @@ export class Client {
dto: any | undefined,
onMessage: (data: T) => void
): Promise<void> {
const state: Record<string, string> = { ...this.state };
for (const i of this.requestInterceptors) {
await i(serviceName, methodName, dto);
await i(serviceName, methodName, state, dto);
}
const res = await fetch(this.url + "/cell", {
method: "POST",
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;
const anyResult: result<any> = { status: 0 };