diff --git a/core/debug/debug/debug.go b/core/debug/debug/debug.go index ef7b0720..fa320a01 100644 --- a/core/debug/debug/debug.go +++ b/core/debug/debug/debug.go @@ -4,7 +4,7 @@ import ( "path/filepath" "sort" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" g "github.com/maragudk/gomponents" c "github.com/maragudk/gomponents/components" h "github.com/maragudk/gomponents/html" @@ -16,7 +16,7 @@ func init() { } func initDebug() { - debug.Get("/", func(ctx *fiber.Ctx) error { + debug.Get("/", func(ctx fiber.Ctx) error { pathMap := make(map[string]interface{}) stack := debug.App().Stack() for m := range stack { diff --git a/core/debug/debug/mux.go b/core/debug/debug/mux.go index 4fac20b1..cf0450eb 100644 --- a/core/debug/debug/mux.go +++ b/core/debug/debug/mux.go @@ -6,7 +6,7 @@ import ( "strings" "sync" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/config" "github.com/pubgo/funk/errors" @@ -27,7 +27,7 @@ var ( func init() { log.Info().Str("password", running.InstanceID).Msg("debug password") - debug.App().Use(func(c *fiber.Ctx) (gErr error) { + debug.App().Use(func(c fiber.Ctx) (gErr error) { defer recovery.Recovery(func(err error) { err = errors.WrapTag(err, errors.T("headers", c.GetReqHeaders()), diff --git a/core/debug/healthy/debug.go b/core/debug/healthy/debug.go index 8f5ca51d..8f8f3d6d 100644 --- a/core/debug/healthy/debug.go +++ b/core/debug/healthy/debug.go @@ -5,14 +5,14 @@ import ( "time" jjson "github.com/goccy/go-json" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/funk/try" "github.com/pubgo/lava/core/debug" "github.com/pubgo/lava/core/healthy" ) func init() { - debug.Get("/health", func(ctx *fiber.Ctx) error { + debug.Get("/health", func(ctx fiber.Ctx) error { dt := make(map[string]*health) for _, name := range healthy.List() { h := &health{} diff --git a/core/debug/mux.go b/core/debug/mux.go index 2cd3f6e7..05b5e891 100644 --- a/core/debug/mux.go +++ b/core/debug/mux.go @@ -4,8 +4,8 @@ import ( "net/http" _ "github.com/fasthttp/router" - "github.com/gofiber/adaptor/v2" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" + adaptor "github.com/gofiber/fiber/v3/middleware/adaptor" ) type Config struct { @@ -16,26 +16,60 @@ type Config struct { var app = fiber.New() -func Handler(ctx *fiber.Ctx) error { +func Handler(ctx fiber.Ctx) error { app.Handler()(ctx.Context()) return nil } -func App() *fiber.App { return app } -func WrapFunc(h http.HandlerFunc) fiber.Handler { return adaptor.HTTPHandlerFunc(h) } -func Wrap(h http.Handler) fiber.Handler { return adaptor.HTTPHandler(h) } -func Get(path string, handlers ...fiber.Handler) { app.Get(path, handlers...) } -func Head(path string, handlers ...fiber.Handler) { app.Head(path, handlers...) } -func Post(path string, handlers ...fiber.Handler) { app.Post(path, handlers...) } -func Put(path string, handlers ...fiber.Handler) { app.Put(path, handlers...) } -func Delete(path string, handlers ...fiber.Handler) { app.Delete(path, handlers...) } -func Connect(path string, handlers ...fiber.Handler) { app.Connect(path, handlers...) } -func Options(path string, handlers ...fiber.Handler) { app.Options(path, handlers...) } -func Trace(path string, handlers ...fiber.Handler) { app.Trace(path, handlers...) } -func Patch(path string, handlers ...fiber.Handler) { app.Patch(path, handlers...) } -func Static(prefix, root string, config ...fiber.Static) { app.Static(prefix, root, config...) } -func All(path string, handlers ...fiber.Handler) { app.All(path, handlers...) } -func Group(prefix string, handlers ...fiber.Handler) { app.Group(prefix, handlers...) } -func Route(prefix string, fn func(router fiber.Router), name ...string) { - app.Route(prefix, fn, name...) +func App() *fiber.App { return app } +func WrapFunc(h http.HandlerFunc) fiber.Handler { return adaptor.HTTPHandlerFunc(h) } +func Wrap(h http.Handler) fiber.Handler { return adaptor.HTTPHandler(h) } +func Get(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Get(path, handlers, middleware...) +} + +func Head(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Head(path, handlers, middleware...) +} + +func Post(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Post(path, handlers, middleware...) +} + +func Put(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Put(path, handlers, middleware...) +} + +func Delete(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Delete(path, handlers, middleware...) +} + +func Connect(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Connect(path, handlers, middleware...) +} + +func Options(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Options(path, handlers, middleware...) +} + +func Trace(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Trace(path, handlers, middleware...) +} + +func Patch(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.Patch(path, handlers, middleware...) +} + +func All(path string, handlers fiber.Handler, middleware ...fiber.Handler) { + app.All(path, handlers, middleware...) +} + +func Group(prefix string, handlers ...fiber.Handler) { + app.Group(prefix, handlers...) +} + +func Route(prefix string, fn func(r fiber.Router)) { fn(app.Use(prefix)) } + +func Use(args ...any) fiber.Router { + return app.Use(args...) } diff --git a/core/debug/pprof/pprof.go b/core/debug/pprof/pprof.go index 03c6b1e1..d0a87e0e 100644 --- a/core/debug/pprof/pprof.go +++ b/core/debug/pprof/pprof.go @@ -5,38 +5,35 @@ import ( "net/http/pprof" "github.com/felixge/fgprof" - "github.com/gofiber/fiber/v2" - + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/lava/core/debug" ) func init() { debug.Get("/gprof/", debug.Wrap(fgprof.Handler())) - debug.Route("/pprof/", func(r fiber.Router) { - r.Get("", debug.WrapFunc(pprof.Index)) - r.Get(":name", func(ctx *fiber.Ctx) error { - name := ctx.Params("name") - switch name { - case "cmdline": - return debug.WrapFunc(pprof.Cmdline)(ctx) - case "profile": - return debug.WrapFunc(pprof.Profile)(ctx) - case "symbol": - return debug.WrapFunc(pprof.Symbol)(ctx) - case "trace": - return debug.WrapFunc(pprof.Trace)(ctx) - case "allocs": - return debug.Wrap(pprof.Handler("allocs"))(ctx) - case "goroutine": - return debug.Wrap(pprof.Handler("goroutine"))(ctx) - case "heap": - return debug.Wrap(pprof.Handler("heap"))(ctx) - case "mutex": - return debug.Wrap(pprof.Handler("mutex"))(ctx) - case "threadcreate": - return debug.Wrap(pprof.Handler("threadcreate"))(ctx) - } - return errors.New("name not found") - }) + debug.Get("/pprof/", debug.WrapFunc(pprof.Index)) + debug.Get("/pprof/:name", func(ctx fiber.Ctx) error { + name := ctx.Params("name") + switch name { + case "cmdline": + return debug.WrapFunc(pprof.Cmdline)(ctx) + case "profile": + return debug.WrapFunc(pprof.Profile)(ctx) + case "symbol": + return debug.WrapFunc(pprof.Symbol)(ctx) + case "trace": + return debug.WrapFunc(pprof.Trace)(ctx) + case "allocs": + return debug.Wrap(pprof.Handler("allocs"))(ctx) + case "goroutine": + return debug.Wrap(pprof.Handler("goroutine"))(ctx) + case "heap": + return debug.Wrap(pprof.Handler("heap"))(ctx) + case "mutex": + return debug.Wrap(pprof.Handler("mutex"))(ctx) + case "threadcreate": + return debug.Wrap(pprof.Handler("threadcreate"))(ctx) + } + return errors.New("name not found") }) } diff --git a/core/debug/process/process.go b/core/debug/process/process.go index c282a716..5fede334 100644 --- a/core/debug/process/process.go +++ b/core/debug/process/process.go @@ -3,7 +3,7 @@ package process import ( "debug/buildinfo" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" ps "github.com/keybase/go-ps" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/generic" @@ -13,7 +13,7 @@ import ( ) func init() { - debug.Get("/process", func(ctx *fiber.Ctx) error { + debug.Get("/process", func(ctx fiber.Ctx) error { processes := assert.Must1(ps.Processes()) processes1 := generic.Map(processes, func(i int) map[string]any { p := processes[i] diff --git a/core/debug/statsviz/main.go b/core/debug/statsviz/main.go index 05dbf315..ecc5be69 100644 --- a/core/debug/statsviz/main.go +++ b/core/debug/statsviz/main.go @@ -4,7 +4,7 @@ import ( "strings" "github.com/arl/statsviz" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/funk/assert" "github.com/pubgo/lava/core/debug" "github.com/pubgo/lava/pkg/httputil" @@ -14,22 +14,21 @@ import ( func init() { srv := assert.Exit1(statsviz.NewServer(statsviz.Root("/statsviz"))) - debug.Route("/statsviz", func(router fiber.Router) { - router.Use(func(ctx *fiber.Ctx) error { - path := string(ctx.Request().URI().Path()) - pathList := strings.Split(path, "/") - if strings.Trim(pathList[len(pathList)-1], "/") == "ws" { - return httputil.HTTPHandler(srv.Ws())(ctx) - } + router := debug.Use("/statsviz") + router.Use(func(ctx fiber.Ctx) error { + path := string(ctx.Request().URI().Path()) + pathList := strings.Split(path, "/") + if strings.Trim(pathList[len(pathList)-1], "/") == "ws" { + return httputil.HTTPHandler(srv.Ws())(ctx) + } - return ctx.Next() - }) + return ctx.Next() + }) - router.Get("/", func(ctx *fiber.Ctx) error { - return httputil.HTTPHandler(srv.Index())(ctx) - }) - router.Get("/*", func(ctx *fiber.Ctx) error { - return httputil.HTTPHandler(srv.Index())(ctx) - }) + router.Get("/", func(ctx fiber.Ctx) error { + return httputil.HTTPHandler(srv.Index())(ctx) + }) + router.Get("/*", func(ctx fiber.Ctx) error { + return httputil.HTTPHandler(srv.Index())(ctx) }) } diff --git a/core/debug/trace/trace.go b/core/debug/trace/trace.go index e94a6cd2..c53fa17f 100644 --- a/core/debug/trace/trace.go +++ b/core/debug/trace/trace.go @@ -1,7 +1,7 @@ package trace import ( - "github.com/gofiber/adaptor/v2" + adaptor "github.com/gofiber/fiber/v3/middleware/adaptor" "golang.org/x/net/trace" "github.com/pubgo/lava/core/debug" diff --git a/core/debug/vars/debug.go b/core/debug/vars/debug.go index 6fa6320b..4a8fbd9f 100644 --- a/core/debug/vars/debug.go +++ b/core/debug/vars/debug.go @@ -4,7 +4,7 @@ import ( "expvar" "fmt" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" g "github.com/maragudk/gomponents" c "github.com/maragudk/gomponents/components" h "github.com/maragudk/gomponents/html" @@ -25,21 +25,20 @@ func init() { return c.HTML5(c.HTML5Props{Title: "/expvar", Body: nodes}) } - debug.Route("/vars", func(r fiber.Router) { - r.Get("/", func(ctx *fiber.Ctx) error { - ctx.Response().Header.SetContentType(fiber.MIMETextHTMLCharsetUTF8) - var keys []string - expvar.Do(func(kv expvar.KeyValue) { - keys = append(keys, fmt.Sprintf("/debug/vars/%s", kv.Key)) - }) - - return index(keys).Render(ctx) + r := debug.Use("/vars") + r.Get("/", func(ctx fiber.Ctx) error { + ctx.Response().Header.SetContentType(fiber.MIMETextHTMLCharsetUTF8) + var keys []string + expvar.Do(func(kv expvar.KeyValue) { + keys = append(keys, fmt.Sprintf("/debug/vars/%s", kv.Key)) }) - r.Get("/:name", func(ctx *fiber.Ctx) error { - name := ctx.Params("name") - ctx.Response().Header.Set("Content-Type", "application/json; charset=utf-8") - return ctx.SendString(expvar.Get(name).String()) - }) + return index(keys).Render(ctx) + }) + + r.Get("/:name", func(ctx fiber.Ctx) error { + name := ctx.Params("name") + ctx.Response().Header.Set("Content-Type", "application/json; charset=utf-8") + return ctx.SendString(expvar.Get(name).String()) }) } diff --git a/core/debug/version/version.go b/core/debug/version/version.go index e8c7ce5a..0e954af0 100644 --- a/core/debug/version/version.go +++ b/core/debug/version/version.go @@ -6,7 +6,7 @@ import ( rd "runtime/debug" json "github.com/goccy/go-json" - "github.com/gofiber/adaptor/v2" + adaptor "github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/running" diff --git a/core/healthy/aaa.go b/core/healthy/aaa.go index 35494985..568a345f 100644 --- a/core/healthy/aaa.go +++ b/core/healthy/aaa.go @@ -1,7 +1,7 @@ package healthy import ( - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" ) -type Handler func(req *fiber.Ctx) error +type Handler func(req fiber.Ctx) error diff --git a/core/metrics/_docs.go b/core/metrics/_docs.go index aaefa2a1..efd452ed 100644 --- a/core/metrics/_docs.go +++ b/core/metrics/_docs.go @@ -1,3 +1,7 @@ package metrics // https://github.com/hashicorp/go-metrics +// https://github.com/VictoriaMetrics/metrics +// github.com/uber-go/tally +// https://github.com/armon/go-metrics +// https://github.com/rcrowley/go-metrics diff --git a/go.mod b/go.mod index 7dc874bd..2ac5ece3 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/pubgo/lava go 1.22.1 require ( - github.com/gofiber/fiber/v2 v2.52.4 github.com/golang/protobuf v1.5.4 // indirect github.com/grandcat/zeroconf v1.0.0 github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 @@ -40,14 +39,15 @@ require ( github.com/arl/statsviz v0.6.0 github.com/dave/jennifer v1.7.0 github.com/ecordell/optgen v0.0.9 + github.com/ettle/strcase v0.2.0 github.com/fasthttp/router v1.5.0 - github.com/fasthttp/websocket v1.5.8 + github.com/fasthttp/websocket v1.5.10 github.com/felixge/fgprof v0.9.5 github.com/fullstorydev/grpchan v1.1.1 github.com/go-playground/validator/v10 v10.19.0 - github.com/gofiber/adaptor/v2 v2.2.1 + github.com/gofiber/fiber/v3 v3.0.0-beta.3 github.com/gofiber/utils v1.1.0 - github.com/gofiber/websocket/v2 v2.2.1 + github.com/gofiber/utils/v2 v2.0.0-beta.7 github.com/golangci/golangci-lint v1.61.0 github.com/gorilla/websocket v1.5.1 github.com/goyek/goyek/v2 v2.2.0 @@ -66,7 +66,7 @@ require ( github.com/stretchr/testify v1.9.0 github.com/uber-go/tally/v4 v4.1.16 github.com/urfave/cli/v3 v3.0.0-alpha9.0.20240717192922-127cf54fac9f - github.com/valyala/fasthttp v1.52.0 + github.com/valyala/fasthttp v1.55.0 github.com/valyala/fasttemplate v1.2.2 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.26.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.26.0 @@ -130,7 +130,6 @@ require ( github.com/deckarep/golang-set/v2 v2.6.0 // indirect github.com/denis-tingaikin/go-header v0.5.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.1.0 // indirect - github.com/ettle/strcase v0.2.0 // indirect github.com/fatih/color v1.17.0 // indirect github.com/fatih/structtag v1.2.0 // indirect github.com/firefart/nonamedreturns v1.0.5 // indirect @@ -245,7 +244,7 @@ require ( github.com/santhosh-tekuri/jsonschema/v5 v5.3.1 // indirect github.com/sashamelentyev/interfacebloat v1.1.0 // indirect github.com/sashamelentyev/usestdlibvars v1.27.0 // indirect - github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511 // indirect + github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 // indirect github.com/securego/gosec/v2 v2.21.2 // indirect github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c // indirect github.com/sirupsen/logrus v1.9.3 // indirect diff --git a/go.sum b/go.sum index ab600e5d..6a35677b 100644 --- a/go.sum +++ b/go.sum @@ -148,8 +148,8 @@ github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q= github.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A= github.com/fasthttp/router v1.5.0 h1:3Qbbo27HAPzwbpRzgiV5V9+2faPkPt3eNuRaDV6LYDA= github.com/fasthttp/router v1.5.0/go.mod h1:FddcKNXFZg1imHcy+uKB0oo/o6yE9zD3wNguqlhWDak= -github.com/fasthttp/websocket v1.5.8 h1:k5DpirKkftIF/w1R8ZzjSgARJrs54Je9YJK37DL/Ah8= -github.com/fasthttp/websocket v1.5.8/go.mod h1:d08g8WaT6nnyvg9uMm8K9zMYyDjfKyj3170AtPRuVU0= +github.com/fasthttp/websocket v1.5.10 h1:bc7NIGyrg1L6sd5pRzCIbXpro54SZLEluZCu0rOpcN4= +github.com/fasthttp/websocket v1.5.10/go.mod h1:BwHeuXGWzCW1/BIKUKD3+qfCl+cTdsHu/f243NcAI/Q= github.com/fatih/color v1.17.0 h1:GlRw1BRJxkpqUCBKzKOw098ed57fEsKeNjpTe3cSjK4= github.com/fatih/color v1.17.0/go.mod h1:YZ7TlrGPkiz6ku9fK3TLD/pl3CpsiFyu8N92HLgmosI= github.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4= @@ -164,6 +164,8 @@ github.com/fsnotify/fsnotify v1.6.0 h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4 github.com/fsnotify/fsnotify v1.6.0/go.mod h1:sl3t1tCWJFWoRz9R8WJCbQihKKwmorjAbSClcnxKAGw= github.com/fullstorydev/grpchan v1.1.1 h1:heQqIJlAv5Cnks9a70GRL2EJke6QQoUB25VGR6TZQas= github.com/fullstorydev/grpchan v1.1.1/go.mod h1:f4HpiV8V6htfY/K44GWV1ESQzHBTq7DinhzqQ95lpgc= +github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E= +github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ= github.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo= github.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA= github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= @@ -235,14 +237,12 @@ github.com/gobwas/ws v1.2.1/go.mod h1:hRKAFb8wOxFROYNsT1bqfWnhX+b5MFeJM9r2ZSwg/K github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= -github.com/gofiber/adaptor/v2 v2.2.1 h1:givE7iViQWlsTR4Jh7tB4iXzrlKBgiraB/yTdHs9Lv4= -github.com/gofiber/adaptor/v2 v2.2.1/go.mod h1:AhR16dEqs25W2FY/l8gSj1b51Azg5dtPDmm+pruNOrc= -github.com/gofiber/fiber/v2 v2.52.4 h1:P+T+4iK7VaqUsq2PALYEfBBo6bJZ4q3FP8cZ84EggTM= -github.com/gofiber/fiber/v2 v2.52.4/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= +github.com/gofiber/fiber/v3 v3.0.0-beta.3 h1:7Q2I+HsIqnIEEDB+9oe7Gadpakh6ZLhXpTYz/L20vrg= +github.com/gofiber/fiber/v3 v3.0.0-beta.3/go.mod h1:kcMur0Dxqk91R7p4vxEpJfDWZ9u5IfvrtQc8Bvv/JmY= github.com/gofiber/utils v1.1.0 h1:vdEBpn7AzIUJRhe+CiTOJdUcTg4Q9RK+pEa0KPbLdrM= github.com/gofiber/utils v1.1.0/go.mod h1:poZpsnhBykfnY1Mc0KeEa6mSHrS3dV0+oBWyeQmb2e0= -github.com/gofiber/websocket/v2 v2.2.1 h1:C9cjxvloojayOp9AovmpQrk8VqvVnT8Oao3+IUygH7w= -github.com/gofiber/websocket/v2 v2.2.1/go.mod h1:Ao/+nyNnX5u/hIFPuHl28a+NIkrqK7PRimyKaj4JxVU= +github.com/gofiber/utils/v2 v2.0.0-beta.7 h1:NnHFrRHvhrufPABdWajcKZejz9HnCWmT/asoxRsiEbQ= +github.com/gofiber/utils/v2 v2.0.0-beta.7/go.mod h1:J/M03s+HMdZdvhAeyh76xT72IfVqBzuz/OJkrMa7cwU= github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= @@ -589,8 +589,8 @@ github.com/sashamelentyev/interfacebloat v1.1.0 h1:xdRdJp0irL086OyW1H/RTZTr1h/tM github.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ= github.com/sashamelentyev/usestdlibvars v1.27.0 h1:t/3jZpSXtRPRf2xr0m63i32ZrusyurIGT9E5wAvXQnI= github.com/sashamelentyev/usestdlibvars v1.27.0/go.mod h1:9nl0jgOfHKWNFS43Ojw0i7aRoS4j6EBye3YBhmAIRF8= -github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511 h1:KanIMPX0QdEdB4R3CiimCAbxFrhB3j7h0/OvpYGVQa8= -github.com/savsgio/gotils v0.0.0-20240303185622-093b76447511/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg= +github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38 h1:D0vL7YNisV2yqE55+q0lFuGse6U8lxlg7fYTctlT5Gc= +github.com/savsgio/gotils v0.0.0-20240704082632-aef3928b8a38/go.mod h1:sM7Mt7uEoCeFSCBM+qBrqvEo+/9vdmj19wzp3yzUhmg= github.com/securego/gosec/v2 v2.21.2 h1:deZp5zmYf3TWwU7A7cR2+SolbTpZ3HQiwFqnzQyEl3M= github.com/securego/gosec/v2 v2.21.2/go.mod h1:au33kg78rNseF5PwPnTWhuYBFf534bvJRvOrgZ/bFzU= github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c h1:W65qqJCIOVP4jpqPQ0YvHYKwcMEMVWIzWC5iNQQfBTU= @@ -683,8 +683,8 @@ github.com/uudashr/gocognit v1.1.3 h1:l+a111VcDbKfynh+airAy/DJQKaXh2m9vkoysMPSZy github.com/uudashr/gocognit v1.1.3/go.mod h1:aKH8/e8xbTRBwjbCkwZ8qt4l2EpKXl31KMHgSS+lZ2U= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.52.0 h1:wqBQpxH71XW0e2g+Og4dzQM8pk34aFYlA1Ga8db7gU0= -github.com/valyala/fasthttp v1.52.0/go.mod h1:hf5C4QnVMkNXMspnsUlfM3WitlgYflyhHYoKol/szxQ= +github.com/valyala/fasthttp v1.55.0 h1:Zkefzgt6a7+bVKHnu/YaYSOPfNYNisSVBo/unVCf8k8= +github.com/valyala/fasthttp v1.55.0/go.mod h1:NkY9JtkrpPKmgwV3HTaS2HWaJss9RSIsRVfcxxoHiOM= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= github.com/valyala/fasttemplate v1.2.2/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= @@ -693,6 +693,8 @@ github.com/vmihailenco/msgpack/v5 v5.4.1 h1:cQriyiUvjTwOHg8QZaPihLWeRAAVoCpE00IU github.com/vmihailenco/msgpack/v5 v5.4.1/go.mod h1:GaZTsDaehaPpQVyxrf5mtQlH+pc21PIudVV/E3rRQok= github.com/vmihailenco/tagparser/v2 v2.0.0 h1:y09buUbR+b5aycVFQs/g70pqKVZNBmxwAhO7/IwNM9g= github.com/vmihailenco/tagparser/v2 v2.0.0/go.mod h1:Wri+At7QHww0WTrCBeu4J6bNtoV6mEfg5OIWRZA9qds= +github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= +github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= github.com/xen0n/gosmopolitan v1.2.2 h1:/p2KTnMzwRexIW8GlKawsTWOxn7UHA+jCMF/V8HHtvU= github.com/xen0n/gosmopolitan v1.2.2/go.mod h1:7XX7Mj61uLYrj0qmeN0zi7XDon9JRAEhYQqAPLVNTeg= github.com/yagipy/maintidx v1.0.0 h1:h5NvIsCz+nRDapQ0exNv4aJ0yXSI0420omVANTv3GJM= diff --git a/lava/router.go b/lava/router.go index a193f0f8..63a339f0 100644 --- a/lava/router.go +++ b/lava/router.go @@ -3,7 +3,7 @@ package lava import ( "context" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "google.golang.org/grpc" ) diff --git a/pkg/fiber_builder/config.go b/pkg/fiber_builder/config.go index 1d13bee7..bdfba034 100644 --- a/pkg/fiber_builder/config.go +++ b/pkg/fiber_builder/config.go @@ -3,7 +3,7 @@ package fiber_builder import ( "time" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/funk/generic" "github.com/pubgo/funk/merge" "github.com/pubgo/funk/recovery" diff --git a/pkg/fiber_builder/websocket.go b/pkg/fiber_builder/websocket.go index 19107be4..febd0044 100644 --- a/pkg/fiber_builder/websocket.go +++ b/pkg/fiber_builder/websocket.go @@ -7,8 +7,8 @@ import ( "time" "github.com/fasthttp/websocket" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/utils" + fiber "github.com/gofiber/fiber/v3" + utils "github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" ) @@ -16,7 +16,7 @@ import ( type WsCfg struct { // Filter defines a function to skip middleware. // Optional. Default: nil - Filter func(*fiber.Ctx) bool + Filter func(fiber.Ctx) bool // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration @@ -42,7 +42,7 @@ type WsCfg struct { // NewWs returns a new `handler func(*Conn)` that upgrades a client to the // websocket protocol, you can pass an optional config. -func NewWs(handler func(*fiber.Ctx, *Conn), config ...WsCfg) fiber.Handler { +func NewWs(handler func(fiber.Ctx, *Conn), config ...WsCfg) fiber.Handler { // Init config var cfg WsCfg if len(config) > 0 { @@ -76,7 +76,7 @@ func NewWs(handler func(*fiber.Ctx, *Conn), config ...WsCfg) fiber.Handler { return false }, } - return func(c *fiber.Ctx) error { + return func(c fiber.Ctx) error { conn := acquireConn() // locals c.Context().VisitUserValues(func(key []byte, value interface{}) { @@ -251,7 +251,7 @@ func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { // IsWebSocketUpgrade returns true if the client requested upgrade to the // WebSocket protocol. -func IsWebSocketUpgrade(c *fiber.Ctx) bool { +func IsWebSocketUpgrade(c fiber.Ctx) bool { return websocket.FastHTTPIsWebSocketUpgrade(c.Context()) } diff --git a/pkg/gateway/aaa.go b/pkg/gateway/aaa.go index 2884f615..102b3b05 100644 --- a/pkg/gateway/aaa.go +++ b/pkg/gateway/aaa.go @@ -5,7 +5,7 @@ import ( "io" "net/http" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/lava/pkg/gateway/internal/routertree" "google.golang.org/grpc" "google.golang.org/grpc/encoding" @@ -22,12 +22,12 @@ type ( SetUnaryInterceptor(interceptor grpc.UnaryServerInterceptor) SetStreamInterceptor(interceptor grpc.StreamServerInterceptor) - SetRequestDecoder(protoreflect.FullName, func(ctx *fiber.Ctx, msg proto.Message) error) - SetResponseEncoder(protoreflect.FullName, func(ctx *fiber.Ctx, msg proto.Message) error) + SetRequestDecoder(protoreflect.FullName, func(ctx fiber.Ctx, msg proto.Message) error) + SetResponseEncoder(protoreflect.FullName, func(ctx fiber.Ctx, msg proto.Message) error) RegisterService(sd *grpc.ServiceDesc, ss interface{}) GetOperation(operation string) *GrpcMethod - Handler(*fiber.Ctx) error + Handler(fiber.Ctx) error ServeHTTP(http.ResponseWriter, *http.Request) GetRouteMethods() []RouteOperation } diff --git a/pkg/gateway/mux.go b/pkg/gateway/mux.go index 169cf53b..36f711bc 100644 --- a/pkg/gateway/mux.go +++ b/pkg/gateway/mux.go @@ -12,8 +12,8 @@ import ( "time" "github.com/fullstorydev/grpchan/inprocgrpc" - "github.com/gofiber/adaptor/v2" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" + adaptor "github.com/gofiber/fiber/v3/middleware/adaptor" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/errors" "github.com/pubgo/funk/generic" @@ -42,9 +42,9 @@ type muxOptions struct { maxReceiveMessageSize int maxSendMessageSize int connectionTimeout time.Duration - errHandler func(err error, ctx *fiber.Ctx) - requestInterceptors map[protoreflect.FullName]func(ctx *fiber.Ctx, msg proto.Message) error - responseInterceptors map[protoreflect.FullName]func(ctx *fiber.Ctx, msg proto.Message) error + errHandler func(err error, ctx fiber.Ctx) + requestInterceptors map[protoreflect.FullName]func(ctx fiber.Ctx, msg proto.Message) error + responseInterceptors map[protoreflect.FullName]func(ctx fiber.Ctx, msg proto.Message) error handlers map[string]*methodWrapper customOperationNames map[string]*methodWrapper } @@ -65,8 +65,8 @@ var ( connectionTimeout: defaultServerConnectionTimeout, files: protoregistry.GlobalFiles, types: protoregistry.GlobalTypes, - responseInterceptors: make(map[protoreflect.FullName]func(ctx *fiber.Ctx, msg proto.Message) error), - requestInterceptors: make(map[protoreflect.FullName]func(ctx *fiber.Ctx, msg proto.Message) error), + responseInterceptors: make(map[protoreflect.FullName]func(ctx fiber.Ctx, msg proto.Message) error), + requestInterceptors: make(map[protoreflect.FullName]func(ctx fiber.Ctx, msg proto.Message) error), handlers: make(map[string]*methodWrapper), customOperationNames: make(map[string]*methodWrapper), } @@ -134,11 +134,11 @@ type Mux struct { func (m *Mux) GetRouteMethods() []RouteOperation { return m.routerTree.List() } -func (m *Mux) SetResponseEncoder(name protoreflect.FullName, f func(ctx *fiber.Ctx, msg proto.Message) error) { +func (m *Mux) SetResponseEncoder(name protoreflect.FullName, f func(ctx fiber.Ctx, msg proto.Message) error) { m.opts.responseInterceptors[name] = f } -func (m *Mux) SetRequestDecoder(name protoreflect.FullName, f func(ctx *fiber.Ctx, msg proto.Message) error) { +func (m *Mux) SetRequestDecoder(name protoreflect.FullName, f func(ctx fiber.Ctx, msg proto.Message) error) { m.opts.requestInterceptors[name] = f } @@ -169,7 +169,7 @@ func (m *Mux) GetOperation(operation string) *GrpcMethod { return handleOperation(opt) } -func (m *Mux) Handler(ctx *fiber.Ctx) error { +func (m *Mux) Handler(ctx fiber.Ctx) error { matchOperation, err := m.routerTree.Match(ctx.Method(), string(ctx.Request().URI().Path())) if err != nil { return errors.WrapCaller(err) diff --git a/pkg/gateway/stream_http.go b/pkg/gateway/stream_http.go index 229b9a98..556a9eb3 100644 --- a/pkg/gateway/stream_http.go +++ b/pkg/gateway/stream_http.go @@ -7,7 +7,7 @@ import ( "net/http" "net/url" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" "github.com/pubgo/funk/errors" "github.com/pubgo/funk/generic" @@ -21,7 +21,7 @@ import ( type streamHTTP struct { method *methodWrapper path *routertree.MatchOperation - handler *fiber.Ctx + handler fiber.Ctx ctx context.Context header metadata.MD params url.Values diff --git a/pkg/httputil/fiber.go b/pkg/httputil/fiber.go index 381cc57b..3e8281c0 100644 --- a/pkg/httputil/fiber.go +++ b/pkg/httputil/fiber.go @@ -7,14 +7,14 @@ import ( "net/http" "strings" - fiber "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/utils" + fiber "github.com/gofiber/fiber/v3" + utils "github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" "github.com/valyala/fasthttp/fasthttpadaptor" ) func StripPrefix(prefix string, hh fiber.Handler) fiber.Handler { - return func(ctx *fiber.Ctx) error { + return func(ctx fiber.Ctx) error { ctx.Request().Header.Set("Path-Prefix", prefix) ctx.Request().SetRequestURI(strings.TrimPrefix(string(ctx.Request().RequestURI()), prefix)) return hh(ctx) @@ -28,9 +28,9 @@ func FastHandler(h fasthttp.RequestHandler) http.Handler { func HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler { return HTTPHandler(h) } func HTTPHandler(h http.Handler) fiber.Handler { - return func(c *fiber.Ctx) error { + return func(ctx fiber.Ctx) error { handler := NewFastHTTPHandler(h) - handler(c.Context()) + handler(ctx.Context()) return nil } } diff --git a/pkg/wsutil/ws.go b/pkg/wsutil/ws.go index 70ebba75..9467b981 100644 --- a/pkg/wsutil/ws.go +++ b/pkg/wsutil/ws.go @@ -6,8 +6,8 @@ import ( "time" "github.com/fasthttp/websocket" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/utils" + fiber "github.com/gofiber/fiber/v3" + utils "github.com/gofiber/utils/v2" "github.com/valyala/fasthttp" ) @@ -15,7 +15,7 @@ import ( type Config struct { // Filter defines a function to skip middleware. // Optional. Default: nil - Filter func(*fiber.Ctx) bool + Filter func(fiber.Ctx) bool // HandshakeTimeout specifies the duration for the handshake to complete. HandshakeTimeout time.Duration @@ -52,7 +52,7 @@ type Config struct { // New returns a new `handler func(*Conn)` that upgrades a client to the // websocket protocol, you can pass an optional config. -func New(ctx *fiber.Ctx, call func(c *websocket.Conn), config ...Config) (err error) { +func New(ctx fiber.Ctx, call func(c *websocket.Conn), config ...Config) (err error) { // Init config var cfg Config if len(config) > 0 { @@ -168,7 +168,7 @@ func IsUnexpectedCloseError(err error, expectedCodes ...int) bool { // IsWebSocketUpgrade returns true if the client requested upgrade to the // WebSocket protocol. -func IsWebSocketUpgrade(c *fiber.Ctx) bool { +func IsWebSocketUpgrade(c fiber.Ctx) bool { return websocket.FastHTTPIsWebSocketUpgrade(c.Context()) } diff --git a/servers/grpcs/config.go b/servers/grpcs/config.go index e6009ee9..64a2bc96 100644 --- a/servers/grpcs/config.go +++ b/servers/grpcs/config.go @@ -14,11 +14,10 @@ type GrpcServerConfigLoader struct { } type Config struct { - EnablePrintRoutes bool `yaml:"enable_print_routes"` - BaseUrl string `yaml:"base_url"` - GrpcConfig *grpc_builder.Config `yaml:"grpc_config"` - EnableCors bool `yaml:"enable_cors"` - EnablePingPong bool `yaml:"enable_ping_pong"` + BaseUrl string `yaml:"base_url"` + GrpcConfig *grpc_builder.Config `yaml:"grpc_config"` + EnableCors bool `yaml:"enable_cors"` + EnablePingPong bool `yaml:"enable_ping_pong"` // unix seconds PingPongTime int32 `yaml:"ping_pong_time"` @@ -30,8 +29,7 @@ type Config struct { func defaultCfg() *Config { return &Config{ - EnablePrintRoutes: true, - BaseUrl: version.Project(), - GrpcConfig: grpc_builder.GetDefaultCfg(), + BaseUrl: version.Project(), + GrpcConfig: grpc_builder.GetDefaultCfg(), } } diff --git a/servers/grpcs/middleware.go b/servers/grpcs/middleware.go index 1136f425..e06fe8c2 100644 --- a/servers/grpcs/middleware.go +++ b/servers/grpcs/middleware.go @@ -5,7 +5,7 @@ import ( "fmt" "time" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" grpcMiddle "github.com/grpc-ecosystem/go-grpc-middleware" "github.com/pubgo/funk/convert" "github.com/pubgo/funk/errors/errutil" @@ -281,7 +281,7 @@ func handlerStreamMiddle(middlewares map[string][]lava.Middleware) grpc.StreamSe } } -func handlerHttpMiddle(middlewares []lava.Middleware) func(fbCtx *fiber.Ctx) error { +func handlerHttpMiddle(middlewares []lava.Middleware) func(fbCtx fiber.Ctx) error { h := func(ctx context.Context, req lava.Request) (lava.Response, error) { reqCtx := req.(*httpRequest) reqCtx.ctx.SetUserContext(ctx) @@ -289,8 +289,8 @@ func handlerHttpMiddle(middlewares []lava.Middleware) func(fbCtx *fiber.Ctx) err } h = lava.Chain(middlewares...).Middleware(h) - return func(ctx *fiber.Ctx) error { + return func(ctx fiber.Ctx) error { _, err := h(ctx.Context(), &httpRequest{ctx: ctx}) - return err + return handlerHttpErr(err) } } diff --git a/servers/grpcs/request.go b/servers/grpcs/request.go index 386555f8..a7bd234d 100644 --- a/servers/grpcs/request.go +++ b/servers/grpcs/request.go @@ -4,7 +4,7 @@ import ( "fmt" "strings" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/lava/lava" "google.golang.org/grpc" ) @@ -38,7 +38,7 @@ func (r *rpcRequest) Stream() bool { return r.stream != nil } var _ lava.Request = (*httpRequest)(nil) type httpRequest struct { - ctx *fiber.Ctx + ctx fiber.Ctx } func (r *httpRequest) Kind() string { return "http" } diff --git a/servers/grpcs/response.go b/servers/grpcs/response.go index a19297d6..7d830098 100644 --- a/servers/grpcs/response.go +++ b/servers/grpcs/response.go @@ -1,7 +1,7 @@ package grpcs import ( - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/lava/lava" "google.golang.org/grpc" ) @@ -21,7 +21,7 @@ func (h *rpcResponse) Stream() bool { return h.stream != nil } var _ lava.Response = (*httpResponse)(nil) type httpResponse struct { - ctx *fiber.Ctx + ctx fiber.Ctx } func (h *httpResponse) Header() *lava.ResponseHeader { return &h.ctx.Response().Header } diff --git a/servers/grpcs/server.go b/servers/grpcs/server.go index 2d14b576..74945e33 100644 --- a/servers/grpcs/server.go +++ b/servers/grpcs/server.go @@ -12,8 +12,8 @@ import ( "strings" "github.com/fullstorydev/grpchan/inprocgrpc" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/cors" + fiber "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/middleware/cors" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/async" @@ -25,6 +25,7 @@ import ( "github.com/pubgo/funk/recovery" "github.com/pubgo/funk/running" "github.com/pubgo/funk/stack" + "github.com/pubgo/funk/typex" "github.com/pubgo/funk/vars" "github.com/pubgo/funk/version" "github.com/pubgo/lava/clients/grpcc" @@ -124,10 +125,9 @@ func (s *serviceImpl) DixInject( httpServer := fiber.New(fiber.Config{ EnableIPValidation: true, - EnablePrintRoutes: conf.EnablePrintRoutes, AppName: version.Project(), BodyLimit: 100 * 1024 * 1024, - ErrorHandler: func(ctx *fiber.Ctx, err error) error { + ErrorHandler: func(ctx fiber.Ctx, err error) error { if err == nil { return nil } @@ -149,7 +149,7 @@ func (s *serviceImpl) DixInject( AllowOriginsFunc: func(origin string) bool { return true }, - AllowMethods: strings.Join([]string{ + AllowMethods: []string{ fiber.MethodGet, fiber.MethodPost, fiber.MethodPut, @@ -157,7 +157,7 @@ func (s *serviceImpl) DixInject( fiber.MethodPatch, fiber.MethodHead, fiber.MethodOptions, - }, ","), + }, //AllowHeaders: "", AllowCredentials: true, //ExposeHeaders: "", @@ -218,7 +218,7 @@ func (s *serviceImpl) DixInject( } } - httpServer.Mount(conf.BaseUrl, app) + httpServer.Use(conf.BaseUrl, app) grpcGateway := runtime.NewServeMux( runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.HTTPBodyMarshaler{ @@ -396,28 +396,32 @@ func (s *serviceImpl) DixInject( grpcServer.RegisterService(h.ServiceDesc(), h) } - apiPrefix1 := assert.Must1(url.JoinPath(conf.BaseUrl, "gw")) - s.log.Info().Str("path", apiPrefix1).Msg("service grpc gateway base path") - httpServer.Group(apiPrefix1, httputil.StripPrefix(apiPrefix1, mux.Handler)) - for _, m := range mux.GetRouteMethods() { - log.Info(). - Str("operation", m.Operation). - Any("rpc-meta", mux.GetOperation(m.Operation).Meta). - Str("http-method", m.Method). - Str("http-path", "/"+strings.Trim(apiPrefix1, "/")+m.Path). - Str("verb", m.Verb). - Any("path-vars", m.Vars). - Str("extras", fmt.Sprintf("%v", m.Extras)). - Msg("grpc gateway router info") - } + typex.DoBlock(func() { + apiPrefix1 := assert.Must1(url.JoinPath(conf.BaseUrl, "gw")) + s.log.Info().Str("path", apiPrefix1).Msg("service grpc gateway base path") + httpServer.Group(apiPrefix1, httputil.StripPrefix(apiPrefix1, mux.Handler)) + for _, m := range mux.GetRouteMethods() { + log.Info(). + Str("operation", m.Operation). + Any("rpc-meta", mux.GetOperation(m.Operation).Meta). + Str("http-method", m.Method). + Str("http-path", "/"+strings.Trim(apiPrefix1, "/")+m.Path). + Str("verb", m.Verb). + Any("path-vars", m.Vars). + Str("extras", fmt.Sprintf("%v", m.Extras)). + Msg("grpc gateway router info") + } + }) - apiPrefix := assert.Must1(url.JoinPath(conf.BaseUrl, "api")) - s.log.Info().Str("path", apiPrefix).Msg("service grpc gateway base path") - httpServer.Group(apiPrefix, httputil.HTTPHandler(http.StripPrefix(apiPrefix, wsproxy.WebsocketProxy(grpcGateway, - wsproxy.WithPingPong(conf.EnablePingPong), - wsproxy.WithTimeWait(conf.PingPongTime), - wsproxy.WithReadLimit(int64(generic.FromPtr(conf.WsReadLimit))), - )))) + typex.DoBlock(func() { + apiPrefix := assert.Must1(url.JoinPath(conf.BaseUrl, "api")) + s.log.Info().Str("path", apiPrefix).Msg("service grpc gateway base path") + httpServer.Group(apiPrefix, httputil.HTTPHandler(http.StripPrefix(apiPrefix, wsproxy.WebsocketProxy(grpcGateway, + wsproxy.WithPingPong(conf.EnablePingPong), + wsproxy.WithTimeWait(conf.PingPongTime), + wsproxy.WithReadLimit(int64(generic.FromPtr(conf.WsReadLimit))), + )))) + }) s.httpServer = httpServer s.grpcServer = grpcServer diff --git a/servers/grpcs/util.go b/servers/grpcs/util.go index 7e3a640e..4ca66997 100644 --- a/servers/grpcs/util.go +++ b/servers/grpcs/util.go @@ -4,8 +4,12 @@ import ( "net/url" "strings" + "github.com/ettle/strcase" "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" "github.com/grpc-ecosystem/grpc-gateway/v2/utilities" + "github.com/pubgo/funk/errors" + "github.com/pubgo/funk/proto/errorpb" + "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" ) @@ -38,3 +42,56 @@ func (*DefaultQueryParser) Parse(msg proto.Message, values url.Values, filter *u return new(runtime.DefaultQueryParser).Parse(msg, values, filter) } + +func handlerHttpErr(err error) error { + if err == nil { + return nil + } + + var errPb *errorpb.ErrCode + if errors.As(err, &errPb) { + if errPb.Message == "" { + errPb.Message = err.Error() + } + } + + if errPb == nil { + sts, ok := status.FromError(err) + if ok && sts != nil { + if len(sts.Details()) > 0 { + errDetail := sts.Details()[0] + if code, ok := errDetail.(*errorpb.Error); ok { + errPb = code.Code + } + + if code, ok := errDetail.(*errorpb.ErrCode); ok { + errPb = code + } + } else { + errPb = &errorpb.ErrCode{ + Message: sts.Message(), + Code: int32(errorpb.Code(sts.Code())), + StatusCode: errorpb.Code(sts.Code()), + Name: "code." + strcase.ToSnake(errorpb.Code(sts.Code()).String()), + Details: sts.Proto().Details, + } + } + } + } + + if errPb == nil { + errPb = &errorpb.ErrCode{ + Message: err.Error(), + StatusCode: errorpb.Code_Internal, + Code: int32(errorpb.Code_Internal), + Name: "code.internal", + } + } + + // skip error + if errPb.StatusCode == errorpb.Code_OK { + return nil + } + + return errors.NewCodeErr(errPb, errors.ParseErrToPb(err)) +} diff --git a/servers/https/httprouter/router.go b/servers/https/httprouter/router.go index 6fc458d1..e45dc147 100644 --- a/servers/https/httprouter/router.go +++ b/servers/https/httprouter/router.go @@ -5,32 +5,32 @@ import ( "net/http" "github.com/go-playground/validator/v10" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" ) -type Handler[Req any, Rsp any] func(ctx *fiber.Ctx, req *Req) (rsp *Rsp, err error) +type Handler[Req any, Rsp any] func(ctx fiber.Ctx, req *Req) (rsp *Rsp, err error) var validate = validator.New() -func WrapHandler[Req, Rsp any](handle func(ctx *fiber.Ctx, req *Req) (rsp *Rsp, err error)) func(ctx *fiber.Ctx) error { - return func(ctx *fiber.Ctx) error { +func WrapHandler[Req, Rsp any](handle func(ctx fiber.Ctx, req *Req) (rsp *Rsp, err error)) func(ctx fiber.Ctx) error { + return func(ctx fiber.Ctx) error { var req Req - if err := ctx.ParamsParser(&req); err != nil { + if err := ctx.Bind().URI(&req); err != nil { return fmt.Errorf("failed to parse params, err:%w", err) } - if err := ctx.QueryParser(&req); err != nil { + if err := ctx.Bind().Query(&req); err != nil { return fmt.Errorf("failed to parse query, err:%w", err) } - if err := ctx.ReqHeaderParser(&req); err != nil { + if err := ctx.Bind().Header(&req); err != nil { return fmt.Errorf("failed to parse req header, err:%w", err) } switch ctx.Method() { case http.MethodPost, http.MethodPut, http.MethodPatch, http.MethodDelete: - if err := ctx.BodyParser(&req); err != nil { + if err := ctx.Bind().Body(&req); err != nil { return fmt.Errorf("failed to parse body, err:%w", err) } } diff --git a/servers/https/init.go b/servers/https/init.go new file mode 100644 index 00000000..a2609ea2 --- /dev/null +++ b/servers/https/init.go @@ -0,0 +1,11 @@ +package https + +import "github.com/gofiber/fiber/v3/binder" + +func init() { + binder.SetParserDecoder(binder.ParserConfig{ + IgnoreUnknownKeys: true, + ZeroEmpty: true, + ParserType: parserTypes, + }) +} diff --git a/servers/https/middleware.go b/servers/https/middleware.go index 8759a21d..edee2169 100644 --- a/servers/https/middleware.go +++ b/servers/https/middleware.go @@ -4,20 +4,21 @@ import ( "context" "reflect" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/binder" "github.com/pubgo/lava/lava" ) -var parserTypes []fiber.ParserType +var parserTypes []binder.ParserType func RegParser(customType interface{}, converter func(string) reflect.Value) { - parserTypes = append(parserTypes, fiber.ParserType{ + parserTypes = append(parserTypes, binder.ParserType{ Customtype: customType, Converter: converter, }) } -func handlerHttpMiddle(middlewares []lava.Middleware) func(fbCtx *fiber.Ctx) error { +func handlerHttpMiddle(middlewares []lava.Middleware) func(fbCtx fiber.Ctx) error { h := func(ctx context.Context, req lava.Request) (lava.Response, error) { reqCtx := req.(*httpRequest) reqCtx.ctx.SetUserContext(ctx) @@ -25,7 +26,7 @@ func handlerHttpMiddle(middlewares []lava.Middleware) func(fbCtx *fiber.Ctx) err } h = lava.Chain(middlewares...).Middleware(h) - return func(ctx *fiber.Ctx) error { + return func(ctx fiber.Ctx) error { _, err := h(ctx.Context(), &httpRequest{ctx: ctx}) return err } diff --git a/servers/https/request.go b/servers/https/request.go index b1c5042b..a59772ef 100644 --- a/servers/https/request.go +++ b/servers/https/request.go @@ -1,7 +1,7 @@ package https import ( - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/lava/lava" ) @@ -9,7 +9,7 @@ import ( var _ lava.Request = (*httpRequest)(nil) type httpRequest struct { - ctx *fiber.Ctx + ctx fiber.Ctx } func (r *httpRequest) Kind() string { return "http" } diff --git a/servers/https/response.go b/servers/https/response.go index a32edee0..c5987330 100644 --- a/servers/https/response.go +++ b/servers/https/response.go @@ -1,7 +1,7 @@ package https import ( - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/lava/lava" ) @@ -9,7 +9,7 @@ import ( var _ lava.Response = (*httpResponse)(nil) type httpResponse struct { - ctx *fiber.Ctx + ctx fiber.Ctx } func (h *httpResponse) Header() *lava.ResponseHeader { return &h.ctx.Response().Header } diff --git a/servers/https/server.go b/servers/https/server.go index e9eaaeab..224036ac 100644 --- a/servers/https/server.go +++ b/servers/https/server.go @@ -5,14 +5,14 @@ import ( "fmt" "net" "net/http" - "strings" "time" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/cors" + fiber "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/middleware/cors" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/async" "github.com/pubgo/funk/errors/errutil" + "github.com/pubgo/funk/generic" "github.com/pubgo/funk/log" "github.com/pubgo/funk/recovery" "github.com/pubgo/funk/running" @@ -72,12 +72,6 @@ func (s *serviceImpl) DixInject( cfg.BaseUrl = "/" + version.Project() } - fiber.SetParserDecoder(fiber.ParserConfig{ - IgnoreUnknownKeys: true, - ZeroEmpty: true, - ParserType: parserTypes, - }) - log = log.WithName("http-server") s.lc = getLifecycle @@ -85,8 +79,7 @@ func (s *serviceImpl) DixInject( s.httpServer = fiber.New(fiber.Config{ EnableIPValidation: true, - ETag: true, - ErrorHandler: func(ctx *fiber.Ctx, err error) error { + ErrorHandler: func(ctx fiber.Ctx, err error) error { if err == nil { return nil } @@ -108,8 +101,8 @@ func (s *serviceImpl) DixInject( AllowOriginsFunc: func(origin string) bool { return true }, - AllowOrigins: "*", - AllowMethods: strings.Join([]string{ + AllowOrigins: generic.ListOf("*"), + AllowMethods: generic.ListOf( fiber.MethodGet, fiber.MethodPost, fiber.MethodPut, @@ -117,10 +110,10 @@ func (s *serviceImpl) DixInject( fiber.MethodPatch, fiber.MethodHead, fiber.MethodOptions, - }, ","), - AllowHeaders: "", + ), + AllowHeaders: nil, AllowCredentials: true, - ExposeHeaders: "", + ExposeHeaders: nil, MaxAge: 0, })) @@ -150,8 +143,8 @@ func (s *serviceImpl) DixInject( } } - s.httpServer.Mount("/debug", debug.App()) - s.httpServer.Mount(cfg.BaseUrl, app) + s.httpServer.Use("/debug", debug.App()) + s.httpServer.Use(cfg.BaseUrl, app) // 网关初始化 if cfg.EnablePrintRouter { diff --git a/servers/tasks/server.go b/servers/tasks/server.go index 587f010a..b4c5fa4d 100644 --- a/servers/tasks/server.go +++ b/servers/tasks/server.go @@ -6,7 +6,7 @@ import ( "net/http" "time" - "github.com/gofiber/fiber/v2" + fiber "github.com/gofiber/fiber/v3" "github.com/pubgo/funk/assert" "github.com/pubgo/funk/async" "github.com/pubgo/funk/errors" @@ -60,8 +60,7 @@ func (s *Server) DixInject( s.httpServer = fiber.New(fiber.Config{ EnableIPValidation: true, - ETag: true, - ErrorHandler: func(ctx *fiber.Ctx, err error) error { + ErrorHandler: func(ctx fiber.Ctx, err error) error { if err == nil { return nil } @@ -77,7 +76,7 @@ func (s *Server) DixInject( }, }) - s.httpServer.Mount("/debug", debug.App()) + s.httpServer.Use("/debug", debug.App()) } func (s *Server) start() { diff --git a/servers/wss/server.go b/servers/wss/server.go index 405ba992..20b76fba 100644 --- a/servers/wss/server.go +++ b/servers/wss/server.go @@ -3,49 +3,53 @@ package wss import ( "log" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/websocket/v2" + _ "github.com/fasthttp/router" + "github.com/fasthttp/websocket" + fiber "github.com/gofiber/fiber/v3" + "github.com/pubgo/lava/pkg/wsutil" ) func init() { app := fiber.New() - app.Use("/ws", func(c *fiber.Ctx) error { + app.Use("/ws", func(c fiber.Ctx) error { // IsWebSocketUpgrade returns true if the client // requested upgrade to the WebSocket protocol. - if websocket.IsWebSocketUpgrade(c) { + if wsutil.IsWebSocketUpgrade(c) { c.Locals("allowed", true) return c.Next() } return fiber.ErrUpgradeRequired }) - app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) { + app.Get("/ws/:id", func(c fiber.Ctx) error { // c.Locals is added to the *websocket.Conn log.Println(c.Locals("allowed")) // true log.Println(c.Params("id")) // 123 log.Println(c.Query("v")) // 1.0 log.Println(c.Cookies("session")) // "" - // websocket.Conn bindings https://pkg.go.dev/github.com/fasthttp/websocket?tab=doc#pkg-index - var ( - mt int - msg []byte - err error - ) - for { - if mt, msg, err = c.ReadMessage(); err != nil { - log.Println("read:", err) - break + return wsutil.New(c, func(conn *websocket.Conn) { + // websocket.Conn bindings https://pkg.go.dev/github.com/fasthttp/websocket?tab=doc#pkg-index + var ( + mt int + msg []byte + err error + ) + for { + if mt, msg, err = conn.ReadMessage(); err != nil { + log.Println("read:", err) + break + } + log.Printf("recv: %s", msg) + + if err = conn.WriteMessage(mt, msg); err != nil { + log.Println("write:", err) + break + } } - log.Printf("recv: %s", msg) - - if err = c.WriteMessage(mt, msg); err != nil { - log.Println("write:", err) - break - } - } - })) + }) + }) log.Fatal(app.Listen(":3000")) // Access the websocket server: ws://localhost:3000/ws/123?v=1.0