From 8632e2b27129f33d8bf9eb6476b006c48ac5bf4e Mon Sep 17 00:00:00 2001 From: qhd <1766646056@qq.com> Date: Tue, 3 Mar 2026 08:51:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E8=B7=AF=E5=BE=84=E8=BF=87?= =?UTF-8?q?=E6=BB=A4=E4=B8=AD=E9=97=B4=E4=BB=B6=E5=8F=8A=E5=90=88=E6=B3=95?= =?UTF-8?q?=E6=B3=A8=E5=86=8C=E8=B7=AF=E5=BE=84=E6=9C=BA=E5=88=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- http/http.go | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/http/http.go b/http/http.go index e5ba5cf..a751095 100644 --- a/http/http.go +++ b/http/http.go @@ -21,8 +21,12 @@ import ( "github.com/gogf/gf/v2/util/gconv" ) -var Httpserver = g.Server() -var Httpclient = g.Client() +var ( + Httpserver = g.Server() + Httpclient = g.Client() + filterPaths = map[string]bool{"/": true, "/*": true, "/api.json": true} + legalRegisteredPaths = make(map[string]bool) +) func init() { err := gtime.SetTimeZone("Asia/Shanghai") @@ -31,12 +35,40 @@ func init() { } //s.Use(common.Cors) //中间件验证 //s.EnablePProf() //启用性能分析 + Httpserver.BindMiddlewareDefault(validateFilterPathMiddleware) Httpserver.SetOpenApiPath("/api.json") Httpserver.SetDumpRouterMap(true) //关闭打印路由注册信息 Httpserver.BindMiddlewareDefault(ghttp.MiddlewareHandlerResponse) Httpclient.SetDiscovery(gsvc.GetRegistry()) } +func validateFilterPathMiddleware(r *ghttp.Request) { + path := r.URL.Path + if filterPaths[path] && !legalRegisteredPaths[path] { + routes := Httpserver.GetRoutes() + for _, route := range routes { + if filterPaths[route.Handler.Router.Uri] && route.Handler.Router.Uri != "/api.json" { + g.Log().Errorf(r.GetCtx(), "路径 %s 中间件 %s 必须通过 SkipMiddleware 注册", route.Handler.Router.Uri, route.Handler.Name) + } + } + r.ExitAll() + } + r.Middleware.Next() +} + +func SkipMiddleware(h func(r *ghttp.Request), path string) (handler ghttp.HandlerFunc) { + if filterPaths[path] { + legalRegisteredPaths[path] = true + } + return func(r *ghttp.Request) { + if filterPaths[path] { + r.Middleware.Next() + return + } + h(r) + } +} + func RouteRegister(controllers []interface{}) { Httpserver.Group("/log", func(group *ghttp.RouterGroup) { group.Middleware(jaeger.NewTracer)