refactor(main): update handler matching logic to use function instead of prefix

This commit is contained in:
wood chen 2024-10-31 08:24:26 +08:00
parent b1b6a430cd
commit c2c6e14736

24
main.go
View File

@ -31,22 +31,26 @@ func main() {
// 创建处理器链 // 创建处理器链
handlers := []struct { handlers := []struct {
pathPrefix string matcher func(*http.Request) bool
handler http.Handler handler http.Handler
}{ }{
// 固定路径处理器 // 固定路径处理器
{ {
pathPrefix: "", // 空字符串表示检查所有 FixedPaths 配置 matcher: func(r *http.Request) bool {
for _, fp := range cfg.FixedPaths {
if strings.HasPrefix(r.URL.Path, fp.Path) {
return true
}
}
return false
},
handler: middleware.FixedPathProxyMiddleware(cfg.FixedPaths)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})), handler: middleware.FixedPathProxyMiddleware(cfg.FixedPaths)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})),
}, },
// 可以在这里添加其他固定路径处理器 // 默认代理处理器
// {
// pathPrefix: "/something",
// handler: someOtherMiddleware(config)(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})),
// },
// 默认代理处理器放在最后
{ {
pathPrefix: "", matcher: func(r *http.Request) bool {
return true // 总是匹配,作为默认处理器
},
handler: proxyHandler, handler: proxyHandler,
}, },
} }
@ -55,7 +59,7 @@ func main() {
mainHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mainHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 遍历所有处理器 // 遍历所有处理器
for _, h := range handlers { for _, h := range handlers {
if h.pathPrefix == "" || strings.HasPrefix(r.URL.Path, h.pathPrefix) { if h.matcher(r) {
h.handler.ServeHTTP(w, r) h.handler.ServeHTTP(w, r)
return return
} }