diff --git a/go.mod b/go.mod index 081c250d..1853eabe 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ replace github.com/imdario/mergo => github.com/imdario/mergo v0.3.16 require ( buf.build/gen/go/prometheus/prometheus/protocolbuffers/go v1.34.2-20240704212942-bbf0a43bf797.2 github.com/anatol/smart.go v0.0.0-20240606135530-b987830bbb40 - github.com/ansrivas/fiberprometheus/v2 v2.6.1 + github.com/ansrivas/fiberprometheus/v2 v2.7.0 github.com/gofiber/fiber/v2 v2.52.5 github.com/golang/snappy v0.0.4 github.com/prometheus/client_golang v1.19.1 @@ -34,7 +34,6 @@ require ( github.com/go-openapi/jsonpointer v0.21.0 // indirect github.com/go-openapi/jsonreference v0.21.0 // indirect github.com/go-openapi/swag v0.23.0 // indirect - github.com/gofiber/adaptor/v2 v2.2.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect github.com/golang/protobuf v1.5.4 // indirect github.com/google/gnostic-models v0.6.8 // indirect diff --git a/go.sum b/go.sum index 1cb151d9..a15f82f0 100644 --- a/go.sum +++ b/go.sum @@ -8,8 +8,8 @@ github.com/anatol/vmtest v0.0.0-20220413190228-7a42f1f6d7b8 h1:t4JGeY9oaF5LB4Rdx github.com/anatol/vmtest v0.0.0-20220413190228-7a42f1f6d7b8/go.mod h1:oPm5wWoqTSkeoPe1Q3sPryTK8o24Jcbwh8dKOiiIobk= github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= -github.com/ansrivas/fiberprometheus/v2 v2.6.1 h1:wac3pXaE6BYYTF04AC6K0ktk6vCD+MnDOJZ3SK66kXM= -github.com/ansrivas/fiberprometheus/v2 v2.6.1/go.mod h1:MloIKvy4yN6hVqlRpJ/jDiR244YnWJaQC0FIqS8A+MY= +github.com/ansrivas/fiberprometheus/v2 v2.7.0 h1:09XiSzG0J7aZp7RviklngdWdDbSybKjhuWAstp003Gg= +github.com/ansrivas/fiberprometheus/v2 v2.7.0/go.mod h1:hSJdO65lfnWW70Qn9uGdXXsUUSkckbhuw5r/KesygpU= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= @@ -31,8 +31,6 @@ github.com/go-openapi/swag v0.23.0/go.mod h1:esZ8ITTYEsH1V2trKHjAN8Ai7xHb8RV+YSZ github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI= github.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8= -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.5 h1:tWoP1MJQjGEe4GB5TUGOi7P2E0ZMMRx5ZTG4rT+yGMo= github.com/gofiber/fiber/v2 v2.52.5/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= @@ -89,6 +87,8 @@ github.com/onsi/ginkgo/v2 v2.17.2 h1:7eMhcy3GimbsA3hEnVKdw/PQM9XN9krpKVXsZdph0/g github.com/onsi/ginkgo/v2 v2.17.2/go.mod h1:nP2DPOQoNsQmsVyv5rDA8JkXQoCs6goXIvr/PRJ1eCc= github.com/onsi/gomega v1.33.1 h1:dsYjIxxSR755MDmKVsaFQTE22ChNBcuuTWgkUDSubOk= github.com/onsi/gomega v1.33.1/go.mod h1:U4R44UsT+9eLIaYRB2a5qajjtQYn0hauxvRm16AVYg0= +github.com/philhofer/fwd v1.1.2 h1:bnDivRJ1EWPjUIRXV5KfORO897HTbpFAQddBdE8t7Gw= +github.com/philhofer/fwd v1.1.2/go.mod h1:qkPdfjR2SIEbspLqpe1tO4n5yICnr2DY7mqEx2tUTP0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -118,6 +118,8 @@ github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JT github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tinylib/msgp v1.1.9 h1:SHf3yoO2sGA0veCJeCBYLHuttAVFHGm2RHgNodW7wQU= +github.com/tinylib/msgp v1.1.9/go.mod h1:BCXGB54lDD8qUEPmiG0cQQUANC4IUQyB2ItS2UDlO/k= github.com/tmc/scp v0.0.0-20170824174625-f7b48647feef h1:7D6Nm4D6f0ci9yttWaKjM1TMAXrH5Su72dojqYGntFY= github.com/tmc/scp v0.0.0-20170824174625-f7b48647feef/go.mod h1:WLFStEdnJXpjK8kd4qKLwQKX/1vrDzp5BcDyiZJBHJM= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= diff --git a/vendor/github.com/ansrivas/fiberprometheus/v2/README.md b/vendor/github.com/ansrivas/fiberprometheus/v2/README.md index b4b01813..83ad0be8 100644 --- a/vendor/github.com/ansrivas/fiberprometheus/v2/README.md +++ b/vendor/github.com/ansrivas/fiberprometheus/v2/README.md @@ -2,6 +2,8 @@ Prometheus middleware for gofiber. +**Note: Requires Go 1.21 and above** + ![Release](https://img.shields.io/github/release/ansrivas/fiberprometheus.svg) [![Discord](https://img.shields.io/badge/discord-join%20channel-7289DA)](https://gofiber.io/discord) ![Test](https://github.com/ansrivas/fiberprometheus/workflows/Test/badge.svg) @@ -14,6 +16,7 @@ Following metrics are available by default: http_requests_total http_request_duration_seconds http_requests_in_progress_total +http_cache_results ``` ### Install v2 @@ -39,17 +42,21 @@ func main() { // This here will appear as a label, one can also use // fiberprometheus.NewWith(servicename, namespace, subsystem ) // or - // NOTE: Following is not available in v1 // labels := map[string]string{"custom_label1":"custom_value1", "custom_label2":"custom_value2"} // fiberprometheus.NewWithLabels(labels, namespace, subsystem ) prometheus := fiberprometheus.New("my-service-name") prometheus.RegisterAt(app, "/metrics") + prometheus.SetSkipPaths([]string{"/ping"}) // Optional: Remove some paths from metrics app.Use(prometheus.Middleware) app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Hello World") }) + app.Get("/ping", func(c *fiber.Ctx) error { + return c.SendString("pong") + }) + app.Post("/some", func(c *fiber.Ctx) error { return c.SendString("Welcome!") }) @@ -58,37 +65,6 @@ func main() { } ``` -### Example using V1 - -```go -package main - -import ( - "github.com/gofiber/fiber" - "github.com/ansrivas/fiberprometheus" -) - -func main() { - app := fiber.New() - - // This here will appear as a label, one can also use - // fiberprometheus.NewWith(servicename, namespace, subsystem ) - prometheus := fiberprometheus.New("my-service-name") - prometheus.RegisterAt(app, "/metrics") - app.Use(prometheus.Middleware) - - app.Get("/", func(c *fiber.Ctx) { - c.Send("Hello World") - }) - - app.Post("/some", func(c *fiber.Ctx) { - c.Send("Welcome!") - }) - - app.Listen(3000) -} -``` - ### Result - Hit the default url at http://localhost:3000 @@ -96,4 +72,4 @@ func main() { ### Grafana Board -- https://grafana.com/grafana/dashboards/14331 \ No newline at end of file +- https://grafana.com/grafana/dashboards/14331 diff --git a/vendor/github.com/ansrivas/fiberprometheus/v2/middleware.go b/vendor/github.com/ansrivas/fiberprometheus/v2/middleware.go index d4c260f8..cfa74457 100644 --- a/vendor/github.com/ansrivas/fiberprometheus/v2/middleware.go +++ b/vendor/github.com/ansrivas/fiberprometheus/v2/middleware.go @@ -25,8 +25,9 @@ import ( "strconv" "time" - "github.com/gofiber/adaptor/v2" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/adaptor" + "github.com/gofiber/fiber/v2/utils" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promauto" "github.com/prometheus/client_golang/prometheus/promhttp" @@ -34,13 +35,21 @@ import ( // FiberPrometheus ... type FiberPrometheus struct { + gatherer prometheus.Gatherer requestsTotal *prometheus.CounterVec requestDuration *prometheus.HistogramVec requestInFlight *prometheus.GaugeVec + cacheHeaderKey string + cacheCounter *prometheus.CounterVec defaultURL string + skipPaths map[string]struct{} } func create(registry prometheus.Registerer, serviceName, namespace, subsystem string, labels map[string]string) *FiberPrometheus { + if registry == nil { + registry = prometheus.NewRegistry() + } + constLabels := make(prometheus.Labels) if serviceName != "" { constLabels["service"] = serviceName @@ -57,6 +66,16 @@ func create(registry prometheus.Registerer, serviceName, namespace, subsystem st }, []string{"status_code", "method", "path"}, ) + + cacheCounter := promauto.With(registry).NewCounterVec( + prometheus.CounterOpts{ + Name: prometheus.BuildFQName(namespace, subsystem, "cache_results"), + Help: "Counts all cache hits by status code, method, and path", + ConstLabels: constLabels, + }, + []string{"status_code", "method", "path", "cache_result"}, + ) + histogram := promauto.With(registry).NewHistogramVec(prometheus.HistogramOpts{ Name: prometheus.BuildFQName(namespace, subsystem, "request_duration_seconds"), Help: "Duration of all HTTP requests by status code, method and path.", @@ -107,18 +126,34 @@ func create(registry prometheus.Registerer, serviceName, namespace, subsystem st ConstLabels: constLabels, }, []string{"method"}) + // If the registerer is also a gatherer, use it, falling back to the + // DefaultGatherer. + gatherer, ok := registry.(prometheus.Gatherer) + if !ok { + gatherer = prometheus.DefaultGatherer + } + return &FiberPrometheus{ + gatherer: gatherer, requestsTotal: counter, requestDuration: histogram, requestInFlight: gauge, + cacheHeaderKey: "X-Cache", + cacheCounter: cacheCounter, defaultURL: "/metrics", } } +// CustomCacheKey allows to set a custom header key for caching +// By default it is set to "X-Cache", the fiber default +func (ps *FiberPrometheus) CustomCacheKey(cacheHeaderKey string) { + ps.cacheHeaderKey = cacheHeaderKey +} + // New creates a new instance of FiberPrometheus middleware // serviceName is available as a const label func New(serviceName string) *FiberPrometheus { - return create(prometheus.DefaultRegisterer, serviceName, "http", "", nil) + return create(nil, serviceName, "http", "", nil) } // NewWith creates a new instance of FiberPrometheus middleware but with an ability @@ -129,7 +164,7 @@ func New(serviceName string) *FiberPrometheus { // For e.g. namespace = "my_app", subsystem = "http" then metrics would be // `my_app_http_requests_total{...,service= "serviceName"}` func NewWith(serviceName, namespace, subsystem string) *FiberPrometheus { - return create(prometheus.DefaultRegisterer, serviceName, namespace, subsystem, nil) + return create(nil, serviceName, namespace, subsystem, nil) } // NewWithLabels creates a new instance of FiberPrometheus middleware but with an ability @@ -141,7 +176,7 @@ func NewWith(serviceName, namespace, subsystem string) *FiberPrometheus { // then then metrics would become // `my_app_http_requests_total{...,key1= "value1", key2= "value2" }` func NewWithLabels(labels map[string]string, namespace, subsystem string) *FiberPrometheus { - return create(prometheus.DefaultRegisterer, "", namespace, subsystem, labels) + return create(nil, "", namespace, subsystem, labels) } // NewWithRegistry creates a new instance of FiberPrometheus middleware but with an ability @@ -160,19 +195,34 @@ func NewWithRegistry(registry prometheus.Registerer, serviceName, namespace, sub func (ps *FiberPrometheus) RegisterAt(app fiber.Router, url string, handlers ...fiber.Handler) { ps.defaultURL = url - h := append(handlers, adaptor.HTTPHandler(promhttp.Handler())) + h := append(handlers, adaptor.HTTPHandler(promhttp.HandlerFor(ps.gatherer, promhttp.HandlerOpts{}))) app.Get(ps.defaultURL, h...) } +// SetSkipPaths allows to set the paths that should be skipped from the metrics +func (ps *FiberPrometheus) SetSkipPaths(paths []string) { + ps.skipPaths = make(map[string]struct{}) + for _, path := range paths { + ps.skipPaths[path] = struct{}{} + } +} + // Middleware is the actual default middleware implementation func (ps *FiberPrometheus) Middleware(ctx *fiber.Ctx) error { - start := time.Now() - method := ctx.Route().Method + path := string(ctx.Request().RequestURI()) - if ctx.Route().Path == ps.defaultURL { + if path == ps.defaultURL { return ctx.Next() } + // Check if the path is in the map of skipped paths + if _, exists := ps.skipPaths[path]; exists { + return ctx.Next() // Skip metrics collection + } + + // Start metrics timer + start := time.Now() + method := ctx.Route().Method ps.requestInFlight.WithLabelValues(method).Inc() defer func() { ps.requestInFlight.WithLabelValues(method).Dec() @@ -191,11 +241,19 @@ func (ps *FiberPrometheus) Middleware(ctx *fiber.Ctx) error { status = ctx.Response().StatusCode() } - path := ctx.Route().Path - + // Get status as string statusCode := strconv.Itoa(status) + + // Update total requests counter ps.requestsTotal.WithLabelValues(statusCode, method, path).Inc() + // Update the cache counter + cacheResult := utils.CopyString(ctx.GetRespHeader(ps.cacheHeaderKey, "")) + if cacheResult != "" { + ps.cacheCounter.WithLabelValues(statusCode, method, path, cacheResult).Inc() + } + + // Update the request duration histogram elapsed := float64(time.Since(start).Nanoseconds()) / 1e9 ps.requestDuration.WithLabelValues(statusCode, method, path).Observe(elapsed) diff --git a/vendor/github.com/gofiber/adaptor/v2/LICENSE b/vendor/github.com/gofiber/adaptor/v2/LICENSE deleted file mode 100644 index ca80106e..00000000 --- a/vendor/github.com/gofiber/adaptor/v2/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 Fiber - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/gofiber/adaptor/v2/README.md b/vendor/github.com/gofiber/adaptor/v2/README.md deleted file mode 100644 index e6dc28b0..00000000 --- a/vendor/github.com/gofiber/adaptor/v2/README.md +++ /dev/null @@ -1,142 +0,0 @@ -# Adaptor - -![Release](https://img.shields.io/github/release/gofiber/adaptor.svg) -[![Discord](https://img.shields.io/badge/discord-join%20channel-7289DA)](https://gofiber.io/discord) -![Test](https://github.com/gofiber/adaptor/workflows/Test/badge.svg) -![Security](https://github.com/gofiber/adaptor/workflows/Security/badge.svg) -![Linter](https://github.com/gofiber/adaptor/workflows/Linter/badge.svg) - -Converter for net/http handlers to/from Fiber request handlers, special thanks to [@arsmn](https://github.com/arsmn)! - -### Install -``` -go get -u github.com/gofiber/fiber/v2 -go get -u github.com/gofiber/adaptor/v2 -``` - -### Functions -| Name | Signature | Description -| :--- | :--- | :--- -| HTTPHandler | `HTTPHandler(h http.Handler) fiber.Handler` | http.Handler -> fiber.Handler -| HTTPHandlerFunc | `HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler` | http.HandlerFunc -> fiber.Handler -| HTTPMiddleware | `HTTPHandlerFunc(mw func(http.Handler) http.Handler) fiber.Handler` | func(http.Handler) http.Handler -> fiber.Handler -| FiberHandler | `FiberHandler(h fiber.Handler) http.Handler` | fiber.Handler -> http.Handler -| FiberHandlerFunc | `FiberHandlerFunc(h fiber.Handler) http.HandlerFunc` | fiber.Handler -> http.HandlerFunc -| FiberApp | `FiberApp(app *fiber.App) http.HandlerFunc` | Fiber app -> http.HandlerFunc -| CopyContextToFiberContex | `CopyContextToFiberContext(context interface{}, requestContext *fasthttp.RequestCtx)` | context.Context -> fasthttp.RequestCtx - -### net/http to Fiber -```go -package main - -import ( - "fmt" - "net/http" - - "github.com/gofiber/adaptor/v2" - "github.com/gofiber/fiber/v2" -) - -func main() { - // New fiber app - app := fiber.New() - - // http.Handler -> fiber.Handler - app.Get("/", adaptor.HTTPHandler(handler(greet))) - - // http.HandlerFunc -> fiber.Handler - app.Get("/func", adaptor.HTTPHandlerFunc(greet)) - - // Listen on port 3000 - app.Listen(":3000") -} - -func handler(f http.HandlerFunc) http.Handler { - return http.HandlerFunc(f) -} - -func greet(w http.ResponseWriter, r *http.Request) { - fmt.Fprint(w, "Hello World!") -} -``` - -### net/http middleware to Fiber -```go -package main - -import ( - "log" - "net/http" - - "github.com/gofiber/adaptor/v2" - "github.com/gofiber/fiber/v2" -) - -func main() { - // New fiber app - app := fiber.New() - - // http middleware -> fiber.Handler - app.Use(adaptor.HTTPMiddleware(logMiddleware)) - - // Listen on port 3000 - app.Listen(":3000") -} - -func logMiddleware(next http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - log.Println("log middleware") - next.ServeHTTP(w, r) - }) -} -``` - -### Fiber Handler to net/http -```go -package main - -import ( - "net/http" - - "github.com/gofiber/adaptor/v2" - "github.com/gofiber/fiber/v2" -) - -func main() { - // fiber.Handler -> http.Handler - http.Handle("/", adaptor.FiberHandler(greet)) - - // fiber.Handler -> http.HandlerFunc - http.HandleFunc("/func", adaptor.FiberHandlerFunc(greet)) - - // Listen on port 3000 - http.ListenAndServe(":3000", nil) -} - -func greet(c *fiber.Ctx) error { - return c.SendString("Hello World!") -} -``` - -### Fiber App to net/http -```go -package main - -import ( - "github.com/gofiber/adaptor/v2" - "github.com/gofiber/fiber/v2" - "net/http" -) -func main() { - app := fiber.New() - - app.Get("/greet", greet) - - // Listen on port 3000 - http.ListenAndServe(":3000", adaptor.FiberApp(app)) -} - -func greet(c *fiber.Ctx) error { - return c.SendString("Hello World!") -} -``` diff --git a/vendor/github.com/gofiber/fiber/v2/LICENSE b/vendor/github.com/gofiber/fiber/v2/LICENSE index 5188bb8b..8f953f33 100644 --- a/vendor/github.com/gofiber/fiber/v2/LICENSE +++ b/vendor/github.com/gofiber/fiber/v2/LICENSE @@ -1,21 +1,21 @@ -MIT License - -Copyright (c) 2019-present Fenny and Contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2019-present Fenny and Contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/gofiber/adaptor/v2/main.go b/vendor/github.com/gofiber/fiber/v2/middleware/adaptor/adaptor.go similarity index 81% rename from vendor/github.com/gofiber/adaptor/v2/main.go rename to vendor/github.com/gofiber/fiber/v2/middleware/adaptor/adaptor.go index b2835530..8bd6f3fe 100644 --- a/vendor/github.com/gofiber/adaptor/v2/main.go +++ b/vendor/github.com/gofiber/fiber/v2/middleware/adaptor/adaptor.go @@ -1,20 +1,17 @@ -// 🚀 Fiber is an Express inspired web framework written in Go with 💖 -// 📌 API Documentation: https://fiber.wiki -// 📝 Github Repository: https://github.com/gofiber/fiber - package adaptor import ( - "io/ioutil" + "io" "net" "net/http" "reflect" "unsafe" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/utils" "github.com/valyala/fasthttp" "github.com/valyala/fasthttp/fasthttpadaptor" + + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/utils" ) // HTTPHandlerFunc wraps net/http handler func to fiber handler @@ -31,6 +28,16 @@ func HTTPHandler(h http.Handler) fiber.Handler { } } +// ConvertRequest converts a fiber.Ctx to a http.Request. +// forServer should be set to true when the http.Request is going to be passed to a http.Handler. +func ConvertRequest(c *fiber.Ctx, forServer bool) (*http.Request, error) { + var req http.Request + if err := fasthttpadaptor.ConvertRequest(c.Context(), &req, forServer); err != nil { + return nil, err //nolint:wrapcheck // This must not be wrapped + } + return &req, nil +} + // CopyContextToFiberContext copies the values of context.Context to a fasthttp.RequestCtx func CopyContextToFiberContext(context interface{}, requestContext *fasthttp.RequestCtx) { contextValues := reflect.ValueOf(context).Elem() @@ -69,6 +76,7 @@ func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler { c.Request().Header.SetMethod(r.Method) c.Request().SetRequestURI(r.RequestURI) c.Request().SetHost(r.Host) + c.Request().Header.SetHost(r.Host) for key, val := range r.Header { for _, v := range val { c.Request().Header.Set(key, v) @@ -76,7 +84,11 @@ func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler { } CopyContextToFiberContext(r.Context(), c.Context()) }) - _ = HTTPHandler(mw(nextHandler))(c) + + if err := HTTPHandler(mw(nextHandler))(c); err != nil { + return err + } + if next { return c.Next() } @@ -106,23 +118,24 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc { defer fasthttp.ReleaseRequest(req) // Convert net/http -> fasthttp request if r.Body != nil { - body, err := ioutil.ReadAll(r.Body) + n, err := io.Copy(req.BodyWriter(), r.Body) + req.Header.SetContentLength(int(n)) + if err != nil { http.Error(w, utils.StatusMessage(fiber.StatusInternalServerError), fiber.StatusInternalServerError) return } - req.Header.SetContentLength(len(body)) - _, _ = req.BodyWriter().Write(body) } req.Header.SetMethod(r.Method) req.SetRequestURI(r.RequestURI) req.SetHost(r.Host) + req.Header.SetHost(r.Host) for key, val := range r.Header { for _, v := range val { req.Header.Set(key, v) } } - if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil && err.(*net.AddrError).Err == "missing port in address" { + if _, _, err := net.SplitHostPort(r.RemoteAddr); err != nil && err.(*net.AddrError).Err == "missing port in address" { //nolint:errorlint, forcetypeassert // overlinting r.RemoteAddr = net.JoinHostPort(r.RemoteAddr, "80") } remoteAddr, err := net.ResolveTCPAddr("tcp", r.RemoteAddr) @@ -141,7 +154,7 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc { // Execute fiber Ctx err := h[0](ctx) if err != nil { - _ = app.Config().ErrorHandler(ctx, err) + _ = app.Config().ErrorHandler(ctx, err) //nolint:errcheck // not needed } } else { // Execute fasthttp Ctx though app.Handler @@ -153,6 +166,6 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc { w.Header().Add(string(k), string(v)) }) w.WriteHeader(fctx.Response.StatusCode()) - _, _ = w.Write(fctx.Response.Body()) + _, _ = w.Write(fctx.Response.Body()) //nolint:errcheck // not needed } } diff --git a/vendor/modules.txt b/vendor/modules.txt index 778c5cbb..1fe6ddec 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -11,8 +11,8 @@ github.com/anatol/smart.go ## explicit; go 1.13 github.com/andybalholm/brotli github.com/andybalholm/brotli/matchfinder -# github.com/ansrivas/fiberprometheus/v2 v2.6.1 -## explicit; go 1.18 +# github.com/ansrivas/fiberprometheus/v2 v2.7.0 +## explicit; go 1.21 github.com/ansrivas/fiberprometheus/v2 # github.com/beorn7/perks v1.0.1 ## explicit; go 1.11 @@ -40,14 +40,12 @@ github.com/go-openapi/jsonreference/internal # github.com/go-openapi/swag v0.23.0 ## explicit; go 1.20 github.com/go-openapi/swag -# github.com/gofiber/adaptor/v2 v2.2.1 -## explicit; go 1.17 -github.com/gofiber/adaptor/v2 # github.com/gofiber/fiber/v2 v2.52.5 ## explicit; go 1.20 github.com/gofiber/fiber/v2 github.com/gofiber/fiber/v2/internal/schema github.com/gofiber/fiber/v2/log +github.com/gofiber/fiber/v2/middleware/adaptor github.com/gofiber/fiber/v2/utils # github.com/gogo/protobuf v1.3.2 ## explicit; go 1.15