From 2d3027eaba3c4926a69989c3ee2efa3246de94ea Mon Sep 17 00:00:00 2001 From: RW Date: Sun, 3 Dec 2023 10:19:13 +0100 Subject: [PATCH 01/51] Update pull_request_template.md --- .github/pull_request_template.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 675ea9ad68..323c265e79 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -30,4 +30,4 @@ Please delete options that are not relevant. ## Commit formatting: -Use emojis on commit messages so it provides an easy way of identifying the purpose or intention of a commit. Check out the emoji cheatsheet here: https://gitmoji.carloscuesta.me/ +Use emojis on commit messages so it provides an easy way of identifying the purpose or intention of a commit. Check out the emoji cheatsheet here: [CONTRIBUTING.md](https://github.com/gofiber/fiber/blob/master/.github/CONTRIBUTING.md#pull-requests-or-commits) From 9bcc7f3978ea81b6f5bbf759594cefed7ef4841d Mon Sep 17 00:00:00 2001 From: RW Date: Sun, 3 Dec 2023 10:20:29 +0100 Subject: [PATCH 02/51] Update v3-changes.md --- .github/PULL_REQUEST_TEMPLATE/v3-changes.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE/v3-changes.md b/.github/PULL_REQUEST_TEMPLATE/v3-changes.md index 3f4b095767..250037be08 100644 --- a/.github/PULL_REQUEST_TEMPLATE/v3-changes.md +++ b/.github/PULL_REQUEST_TEMPLATE/v3-changes.md @@ -41,5 +41,4 @@ Before you submit your pull request, please make sure you meet these requirement ## Commit Formatting -Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. You can refer to the emoji cheatsheet here: https://gitmoji.carloscuesta.me/ - +Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: [CONTRIBUTING.md](https://github.com/gofiber/fiber/blob/master/.github/CONTRIBUTING.md#pull-requests-or-commits) From a80b288592d1a15616b2c8f944e8b8b63f4af8d9 Mon Sep 17 00:00:00 2001 From: tokelo-12 <113810058+tokelo-12@users.noreply.github.com> Date: Tue, 5 Dec 2023 16:21:03 +0200 Subject: [PATCH 03/51] Update CONTRIBUTING.md (#2752) Grammar correction. --- .github/CONTRIBUTING.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d23c99af24..e35ce19942 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -15,7 +15,7 @@ Titles always we must use prefix according to below: - 📚 Doc: Translate to Portuguese middleware redirect - 🎨 Style: Respected pattern Golint -All pull request that contains a feature or fix is mandatory to have unit tests. Your PR is only to be merged if you respect this flow. +All pull requests that contain a feature or fix are mandatory to have unit tests. Your PR is only to be merged if you respect this flow. # 👍 Contribute From e4d7e84335e2b01bf3dfd03d13483bafa4700a3c Mon Sep 17 00:00:00 2001 From: Jason McNeil Date: Thu, 7 Dec 2023 03:39:41 -0400 Subject: [PATCH 04/51] chore(encryptcookie)!: update default config (#2753) * chore(encryptcookie)!: update default config docs(encryptcookie): enhance documentation and examples BREAKING CHANGE: removed the hardcoded "csrf_" from the Except. * docs(encryptcookie): reads or modifies cookies * chore(encryptcookie): csrf config example * docs(encryptcookie): md table spacing --- docs/api/middleware/encryptcookie.md | 58 ++++++++++++++++------------ middleware/encryptcookie/config.go | 2 +- 2 files changed, 35 insertions(+), 25 deletions(-) diff --git a/docs/api/middleware/encryptcookie.md b/docs/api/middleware/encryptcookie.md index 743578bd87..c6e689e0e8 100644 --- a/docs/api/middleware/encryptcookie.md +++ b/docs/api/middleware/encryptcookie.md @@ -4,7 +4,11 @@ id: encryptcookie # Encrypt Cookie -Encrypt middleware for [Fiber](https://github.com/gofiber/fiber) which encrypts cookie values. Note: this middleware does not encrypt cookie names. +Encrypt Cookie is a middleware for [Fiber](https://github.com/gofiber/fiber) that secures your cookie values through encryption. + +:::note +This middleware encrypts cookie values and not the cookie names. +::: ## Signatures @@ -18,7 +22,7 @@ func GenerateKey() string ## Examples -Import the middleware package that is part of the Fiber web framework +To use the Encrypt Cookie middleware, first, import the middleware package as part of the Fiber web framework: ```go import ( @@ -27,23 +31,20 @@ import ( ) ``` -After you initiate your Fiber app, you can use the following possibilities: +Once you've imported the middleware package, you can use it inside your Fiber app: ```go -// Provide a minimal config -// `Key` must be a 32 character string. It's used to encrypt the values, so make sure it is random and keep it secret. -// You can run `openssl rand -base64 32` or call `encryptcookie.GenerateKey()` to create a random key for you. -// Make sure not to set `Key` to `encryptcookie.GenerateKey()` because that will create a new key every run. +// Provide a minimal configuration app.Use(encryptcookie.New(encryptcookie.Config{ Key: "secret-thirty-2-character-string", })) -// Get / reading out the encrypted cookie +// Retrieve the encrypted cookie value app.Get("/", func(c *fiber.Ctx) error { return c.SendString("value=" + c.Cookies("test")) }) -// Post / create the encrypted cookie +// Create an encrypted cookie app.Post("/", func(c *fiber.Ctx) error { c.Cookie(&fiber.Cookie{ Name: "test", @@ -53,39 +54,48 @@ app.Post("/", func(c *fiber.Ctx) error { }) ``` +:::note +`Key` must be a 32 character string. It's used to encrypt the values, so make sure it is random and keep it secret. +You can run `openssl rand -base64 32` or call `encryptcookie.GenerateKey()` to create a random key for you. +Make sure not to set `Key` to `encryptcookie.GenerateKey()` because that will create a new key every run. +::: + ## Config -| Property | Type | Description | Default | -|:----------|:----------------------------------------------------|:----------------------------------------------------------------------------------------------------|:-----------------------------| -| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | -| Except | `[]string` | Array of cookie keys that should not be encrypted. | `[]` | -| Key | `string` | Base64 encoded unique key to encode & decode cookies. Required. Key length should be 32 characters. | (No default, required field) | -| Encryptor | `func(decryptedString, key string) (string, error)` | Custom function to encrypt cookies. | `EncryptCookie` | -| Decryptor | `func(encryptedString, key string) (string, error)` | Custom function to decrypt cookies. | `DecryptCookie` | +| Property | Type | Description | Default | +|:----------|:----------------------------------------------------|:------------------------------------------------------------------------------------------------------|:-----------------------------| +| Next | `func(*fiber.Ctx) bool` | A function to skip this middleware when returned true. | `nil` | +| Except | `[]string` | Array of cookie keys that should not be encrypted. | `[]` | +| Key | `string` | A base64-encoded unique key to encode & decode cookies. Required. Key length should be 32 characters. | (No default, required field) | +| Encryptor | `func(decryptedString, key string) (string, error)` | A custom function to encrypt cookies. | `EncryptCookie` | +| Decryptor | `func(encryptedString, key string) (string, error)` | A custom function to decrypt cookies. | `DecryptCookie` | ## Default Config ```go var ConfigDefault = Config{ Next: nil, - Except: []string{"csrf_"}, + Except: []string{}, Key: "", Encryptor: EncryptCookie, Decryptor: DecryptCookie, } ``` -## Usage of CSRF and Encryptcookie Middlewares with Custom Cookie Names -Normally, encryptcookie middleware skips `csrf_` cookies. However, it won't work when you use custom cookie names for CSRF. You should update `Except` config to avoid this problem. For example: +## Usage With Other Middlewares That Reads Or Modify Cookies +Place the encryptcookie middleware before any other middleware that reads or modifies cookies. For example, if you are using the CSRF middleware, ensure that the encryptcookie middleware is placed before it. Failure to do so may prevent the CSRF middleware from reading the encrypted cookie. + +You may also choose to exclude certain cookies from encryption. For instance, if you are using the CSRF middleware with a frontend framework like Angular, and the framework reads the token from a cookie, you should exclude that cookie from encryption. This can be achieved by adding the cookie name to the Except array in the configuration: ```go app.Use(encryptcookie.New(encryptcookie.Config{ - Key: "secret-thirty-2-character-string", - Except: []string{"csrf_1"}, // exclude CSRF cookie + Key: "secret-thirty-2-character-string", + Except: []string{csrf.ConfigDefault.CookieName}, // exclude CSRF cookie })) app.Use(csrf.New(csrf.Config{ - KeyLookup: "form:test", - CookieName: "csrf_1", - CookieHTTPOnly: true, + KeyLookup: "header:" + csrf.HeaderName, + CookieSameSite: "Lax", + CookieSecure: true, + CookieHTTPOnly: false, })) ``` diff --git a/middleware/encryptcookie/config.go b/middleware/encryptcookie/config.go index c49fc16ebb..731ac07d79 100644 --- a/middleware/encryptcookie/config.go +++ b/middleware/encryptcookie/config.go @@ -36,7 +36,7 @@ type Config struct { // ConfigDefault is the default config var ConfigDefault = Config{ Next: nil, - Except: []string{"csrf_"}, + Except: []string{}, Key: "", Encryptor: EncryptCookie, Decryptor: DecryptCookie, From 8aa88689ae276affecb50956120df54a16eb2b3b Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 7 Dec 2023 15:14:33 +0100 Subject: [PATCH 05/51] build(deps): bump actions/setup-go from 4 to 5 (#2754) Bumps [actions/setup-go](https://github.com/actions/setup-go) from 4 to 5. - [Release notes](https://github.com/actions/setup-go/releases) - [Commits](https://github.com/actions/setup-go/compare/v4...v5) --- updated-dependencies: - dependency-name: actions/setup-go dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/benchmark.yml | 2 +- .github/workflows/linter.yml | 2 +- .github/workflows/test.yml | 2 +- .github/workflows/vulncheck.yml | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index cbef15c3b3..7625373255 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -22,7 +22,7 @@ jobs: uses: actions/checkout@v4 - name: Install Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: # NOTE: Keep this in sync with the version from go.mod go-version: "1.20.x" diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 37c53168a5..3defb96344 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -17,7 +17,7 @@ jobs: steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: # NOTE: Keep this in sync with the version from go.mod go-version: "1.20.x" diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c11960f478..f103d914fb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,7 +26,7 @@ jobs: uses: actions/checkout@v4 - name: Install Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: ${{ matrix.go-version }} diff --git a/.github/workflows/vulncheck.yml b/.github/workflows/vulncheck.yml index 85e96fdd00..e6d29ccb4b 100644 --- a/.github/workflows/vulncheck.yml +++ b/.github/workflows/vulncheck.yml @@ -25,7 +25,7 @@ jobs: uses: actions/checkout@v4 - name: Install Go - uses: actions/setup-go@v4 + uses: actions/setup-go@v5 with: go-version: "stable" check-latest: true From c441bdf2d026e890df21ae3aa89c8e6a638df3c5 Mon Sep 17 00:00:00 2001 From: iRedMail <2048991+iredmail@users.noreply.github.com> Date: Fri, 8 Dec 2023 17:36:43 +0800 Subject: [PATCH 06/51] =?UTF-8?q?=F0=9F=A9=B9=20middleware/logger/:=20log?= =?UTF-8?q?=20client=20IP=20address=20by=20default=20(#2755)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * middleware/logger: Log client IP address by default. * Update doc. --- docs/api/middleware/logger.md | 4 ++-- middleware/logger/config.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index a01e9bd54c..97c3c73872 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -97,7 +97,7 @@ app.Use(logger.New(logger.Config{ | Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | | Done | `func(*fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` | | CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` | -| Format | `string` | Format defines the logging tags. | `[${time}] ${status} - ${latency} ${method} ${path}\n` | +| Format | `string` | Format defines the logging tags. | `[${time}] ${ip} ${status} - ${latency} ${method} ${path}\n` | | TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` | | TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` | | TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` | @@ -112,7 +112,7 @@ app.Use(logger.New(logger.Config{ var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "[${time}] ${status} - ${latency} ${method} ${path}\n", + Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/logger/config.go b/middleware/logger/config.go index 5b91a065ee..10b382b925 100644 --- a/middleware/logger/config.go +++ b/middleware/logger/config.go @@ -28,7 +28,7 @@ type Config struct { // Format defines the logging tags // - // Optional. Default: [${time}] ${status} - ${latency} ${method} ${path}\n + // Optional. Default: [${time}] ${ip} ${status} - ${latency} ${method} ${path}\n Format string // TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html @@ -86,7 +86,7 @@ type LogFunc func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (i var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "[${time}] ${status} - ${latency} ${method} ${path}\n", + Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, From b1850834a341da80691e23afc5568b7a053fdffa Mon Sep 17 00:00:00 2001 From: Benjamin Grosse Date: Tue, 12 Dec 2023 05:55:29 -0800 Subject: [PATCH 07/51] fix: don't constrain middlewares' context-keys to strings :bug: (#2751) * Revert "Revert ":bug: requestid.Config.ContextKey is interface{} (#2369)" (#2742)" This reverts commit 28be17f929cfa7d3c27dd292fc3956f2f9882e22. * fix: request ContextKey default value condition Should check for `nil` since it is `any`. * fix: don't constrain middlewares' context-keys to strings `context` recommends using "unexported type" as context keys to avoid collisions https://pkg.go.dev/github.com/gofiber/fiber/v2#Ctx.Locals. The official go blog also recommends this https://go.dev/blog/context. `fiber.Ctx.Locals(key any, value any)` correctly allows consumers to use unexported types or e.g. strings. But some fiber middlewares constrain their context-keys to `string` in their "default config structs", making it impossible to use unexported types. This PR removes the `string` _constraint_ from all middlewares, allowing to now use unexported types as per the official guidelines. However the default value is still a string, so it's not a breaking change, and anyone still using strings as context keys is not affected. --- docs/api/middleware/basicauth.md | 4 ++-- docs/api/middleware/csrf.md | 4 ++-- docs/api/middleware/keyauth.md | 2 +- docs/api/middleware/requestid.md | 2 +- middleware/adaptor/adaptor_test.go | 5 +++-- middleware/basicauth/config.go | 8 +++---- middleware/csrf/config.go | 6 ++--- middleware/csrf/csrf.go | 2 +- middleware/idempotency/idempotency.go | 6 +++-- middleware/keyauth/config.go | 4 ++-- middleware/requestid/config.go | 8 ++++--- middleware/requestid/requestid_test.go | 31 +++++++++++++++++++++++--- 12 files changed, 56 insertions(+), 26 deletions(-) diff --git a/docs/api/middleware/basicauth.md b/docs/api/middleware/basicauth.md index 0e90eafed0..d0f3609bde 100644 --- a/docs/api/middleware/basicauth.md +++ b/docs/api/middleware/basicauth.md @@ -67,8 +67,8 @@ app.Use(basicauth.New(basicauth.Config{ | Realm | `string` | Realm is a string to define the realm attribute of BasicAuth. The realm identifies the system to authenticate against and can be used by clients to save credentials. | `"Restricted"` | | Authorizer | `func(string, string) bool` | Authorizer defines a function to check the credentials. It will be called with a username and password and is expected to return true or false to indicate approval. | `nil` | | Unauthorized | `fiber.Handler` | Unauthorized defines the response body for unauthorized responses. | `nil` | -| ContextUsername | `string` | ContextUsername is the key to store the username in Locals. | `"username"` | -| ContextPassword | `string` | ContextPassword is the key to store the password in Locals. | `"password"` | +| ContextUsername | `interface{}` | ContextUsername is the key to store the username in Locals. | `"username"` | +| ContextPassword | `interface{}` | ContextPassword is the key to store the password in Locals. | `"password"` | ## Default Config diff --git a/docs/api/middleware/csrf.md b/docs/api/middleware/csrf.md index 2c30ed5cbe..536e8a4b2d 100644 --- a/docs/api/middleware/csrf.md +++ b/docs/api/middleware/csrf.md @@ -152,14 +152,14 @@ app.Use(csrf.New(csrf.Config{ | Storage | `fiber.Storage` | Store is used to store the state of the middleware. | `nil` | | Session | `*session.Store` | Session is used to store the state of the middleware. Overrides Storage if set. | `nil` | | SessionKey | `string` | SessionKey is the key used to store the token within the session. | "fiber.csrf.token" | -| ContextKey | `string` | Context key to store the generated CSRF token into the context. If left empty, the token will not be stored within the context. | "" | +| ContextKey | `inteface{}` | Context key to store the generated CSRF token into the context. If left empty, the token will not be stored within the context. | "" | | KeyGenerator | `func() string` | KeyGenerator creates a new CSRF token. | utils.UUID | | CookieExpires | `time.Duration` (Deprecated) | Deprecated: Please use Expiration. | 0 | | Cookie | `*fiber.Cookie` (Deprecated) | Deprecated: Please use Cookie* related fields. | `nil` | | TokenLookup | `string` (Deprecated) | Deprecated: Please use KeyLookup. | "" | | ErrorHandler | `fiber.ErrorHandler` | ErrorHandler is executed when an error is returned from fiber.Handler. | DefaultErrorHandler | | Extractor | `func(*fiber.Ctx) (string, error)` | Extractor returns the CSRF token. If set, this will be used in place of an Extractor based on KeyLookup. | Extractor based on KeyLookup | -| HandlerContextKey | `string` | HandlerContextKey is used to store the CSRF Handler into context. | "fiber.csrf.handler" | +| HandlerContextKey | `interface{}` | HandlerContextKey is used to store the CSRF Handler into context. | "fiber.csrf.handler" | ### Default Config diff --git a/docs/api/middleware/keyauth.md b/docs/api/middleware/keyauth.md index ecabe122e7..1a719c134d 100644 --- a/docs/api/middleware/keyauth.md +++ b/docs/api/middleware/keyauth.md @@ -221,7 +221,7 @@ curl --header "Authorization: Bearer my-super-secret-key" http://localhost:3000 | KeyLookup | `string` | KeyLookup is a string in the form of "`:`" that is used to extract key from the request. | "header:Authorization" | | AuthScheme | `string` | AuthScheme to be used in the Authorization header. | "Bearer" | | Validator | `func(*fiber.Ctx, string) (bool, error)` | Validator is a function to validate the key. | A function for key validation | -| ContextKey | `string` | Context key to store the bearer token from the token into context. | "token" | +| ContextKey | `interface{}` | Context key to store the bearer token from the token into context. | "token" | ## Default Config diff --git a/docs/api/middleware/requestid.md b/docs/api/middleware/requestid.md index 112d21d48a..c8ca8d599e 100644 --- a/docs/api/middleware/requestid.md +++ b/docs/api/middleware/requestid.md @@ -45,7 +45,7 @@ app.Use(requestid.New(requestid.Config{ | Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | | Header | `string` | Header is the header key where to get/set the unique request ID. | "X-Request-ID" | | Generator | `func() string` | Generator defines a function to generate the unique identifier. | utils.UUID | -| ContextKey | `string` | ContextKey defines the key used when storing the request ID in the locals for a specific request. | "requestid" | +| ContextKey | `interface{}` | ContextKey defines the key used when storing the request ID in the locals for a specific request. | "requestid" | ## Default Config The default config uses a fast UUID generator which will expose the number of diff --git a/middleware/adaptor/adaptor_test.go b/middleware/adaptor/adaptor_test.go index 340c05c04b..6e03b05a2d 100644 --- a/middleware/adaptor/adaptor_test.go +++ b/middleware/adaptor/adaptor_test.go @@ -36,7 +36,8 @@ func Test_HTTPHandler(t *testing.T) { expectedURL, err := url.ParseRequestURI(expectedRequestURI) utils.AssertEqual(t, nil, err) - expectedContextKey := "contextKey" + type contextKeyType string + expectedContextKey := contextKeyType("contextKey") expectedContextValue := "contextValue" callsCount := 0 @@ -293,7 +294,7 @@ func testFiberToHandlerFunc(t *testing.T, checkDefaultPort bool, app ...*fiber.A utils.AssertEqual(t, expectedResponseBody, string(w.body), "Body") } -func setFiberContextValueMiddleware(next fiber.Handler, key string, value interface{}) fiber.Handler { +func setFiberContextValueMiddleware(next fiber.Handler, key, value interface{}) fiber.Handler { return func(c *fiber.Ctx) error { c.Locals(key, value) return next(c) diff --git a/middleware/basicauth/config.go b/middleware/basicauth/config.go index 3845e91538..d69f48be67 100644 --- a/middleware/basicauth/config.go +++ b/middleware/basicauth/config.go @@ -44,12 +44,12 @@ type Config struct { // ContextUser is the key to store the username in Locals // // Optional. Default: "username" - ContextUsername string + ContextUsername interface{} // ContextPass is the key to store the password in Locals // // Optional. Default: "password" - ContextPassword string + ContextPassword interface{} } // ConfigDefault is the default config @@ -95,10 +95,10 @@ func configDefault(config ...Config) Config { return c.SendStatus(fiber.StatusUnauthorized) } } - if cfg.ContextUsername == "" { + if cfg.ContextUsername == nil { cfg.ContextUsername = ConfigDefault.ContextUsername } - if cfg.ContextPassword == "" { + if cfg.ContextPassword == nil { cfg.ContextPassword = ConfigDefault.ContextPassword } return cfg diff --git a/middleware/csrf/config.go b/middleware/csrf/config.go index 539e84967c..9ab6cab063 100644 --- a/middleware/csrf/config.go +++ b/middleware/csrf/config.go @@ -93,7 +93,7 @@ type Config struct { // If left empty, token will not be stored in context. // // Optional. Default: "" - ContextKey string + ContextKey interface{} // KeyGenerator creates a new CSRF token // @@ -124,7 +124,7 @@ type Config struct { // HandlerContextKey is used to store the CSRF Handler into context // // Default: "fiber.csrf.handler" - HandlerContextKey string + HandlerContextKey interface{} } const HeaderName = "X-Csrf-Token" @@ -204,7 +204,7 @@ func configDefault(config ...Config) Config { if cfg.SessionKey == "" { cfg.SessionKey = ConfigDefault.SessionKey } - if cfg.HandlerContextKey == "" { + if cfg.HandlerContextKey == nil { cfg.HandlerContextKey = ConfigDefault.HandlerContextKey } diff --git a/middleware/csrf/csrf.go b/middleware/csrf/csrf.go index f4dee74c8e..939daaea79 100644 --- a/middleware/csrf/csrf.go +++ b/middleware/csrf/csrf.go @@ -129,7 +129,7 @@ func New(config ...Config) fiber.Handler { c.Vary(fiber.HeaderCookie) // Store the token in the context if a context key is specified - if cfg.ContextKey != "" { + if cfg.ContextKey != nil { c.Locals(cfg.ContextKey, token) } diff --git a/middleware/idempotency/idempotency.go b/middleware/idempotency/idempotency.go index 604f867c76..5affc59620 100644 --- a/middleware/idempotency/idempotency.go +++ b/middleware/idempotency/idempotency.go @@ -12,9 +12,11 @@ import ( // Inspired by https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header-02 // and https://github.com/penguin-statistics/backend-next/blob/f2f7d5ba54fc8a58f168d153baa17b2ad4a14e45/internal/pkg/middlewares/idempotency.go +type localsKeys string + const ( - localsKeyIsFromCache = "idempotency_isfromcache" - localsKeyWasPutToCache = "idempotency_wasputtocache" + localsKeyIsFromCache localsKeys = "idempotency_isfromcache" + localsKeyWasPutToCache localsKeys = "idempotency_wasputtocache" ) func IsFromCache(c *fiber.Ctx) bool { diff --git a/middleware/keyauth/config.go b/middleware/keyauth/config.go index 39d71b6305..c762d72ce6 100644 --- a/middleware/keyauth/config.go +++ b/middleware/keyauth/config.go @@ -41,7 +41,7 @@ type Config struct { // Context key to store the bearertoken from the token into context. // Optional. Default: "token". - ContextKey string + ContextKey interface{} } // ConfigDefault is the default config @@ -87,7 +87,7 @@ func configDefault(config ...Config) Config { if cfg.Validator == nil { panic("fiber: keyauth middleware requires a validator function") } - if cfg.ContextKey == "" { + if cfg.ContextKey == nil { cfg.ContextKey = ConfigDefault.ContextKey } diff --git a/middleware/requestid/config.go b/middleware/requestid/config.go index b3b605e590..b535ec9033 100644 --- a/middleware/requestid/config.go +++ b/middleware/requestid/config.go @@ -24,9 +24,11 @@ type Config struct { // ContextKey defines the key used when storing the request ID in // the locals for a specific request. + // Should be a private type instead of string, but too many apps probably + // rely on this exact value. // - // Optional. Default: requestid - ContextKey string + // Optional. Default: "requestid" + ContextKey interface{} } // ConfigDefault is the default config @@ -57,7 +59,7 @@ func configDefault(config ...Config) Config { if cfg.Generator == nil { cfg.Generator = ConfigDefault.Generator } - if cfg.ContextKey == "" { + if cfg.ContextKey == nil { cfg.ContextKey = ConfigDefault.ContextKey } return cfg diff --git a/middleware/requestid/requestid_test.go b/middleware/requestid/requestid_test.go index 451e96b4b2..b2dc2ac7bf 100644 --- a/middleware/requestid/requestid_test.go +++ b/middleware/requestid/requestid_test.go @@ -55,20 +55,45 @@ func Test_RequestID_Next(t *testing.T) { func Test_RequestID_Locals(t *testing.T) { t.Parallel() reqID := "ThisIsARequestId" - ctxKey := "ThisIsAContextKey" + type ContextKey int + const requestContextKey ContextKey = iota app := fiber.New() app.Use(New(Config{ Generator: func() string { return reqID }, - ContextKey: ctxKey, + ContextKey: requestContextKey, })) var ctxVal string app.Use(func(c *fiber.Ctx) error { - ctxVal = c.Locals(ctxKey).(string) //nolint:forcetypeassert,errcheck // We always store a string in here + ctxVal = c.Locals(requestContextKey).(string) //nolint:forcetypeassert,errcheck // We always store a string in here + return c.Next() + }) + + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, reqID, ctxVal) +} + +// go test -run Test_RequestID_DefaultKey +func Test_RequestID_DefaultKey(t *testing.T) { + t.Parallel() + reqID := "ThisIsARequestId" + + app := fiber.New() + app.Use(New(Config{ + Generator: func() string { + return reqID + }, + })) + + var ctxVal string + + app.Use(func(c *fiber.Ctx) error { + ctxVal = c.Locals("requestid").(string) //nolint:forcetypeassert,errcheck // We always store a string in here return c.Next() }) From 090acbbc5d50a06a678620fa87352ea2530b9906 Mon Sep 17 00:00:00 2001 From: Mehmet Firat KOMURCU Date: Wed, 13 Dec 2023 10:52:16 +0300 Subject: [PATCH 08/51] =?UTF-8?q?=F0=9F=93=9A=20Update=20app.md=20for=20in?= =?UTF-8?q?dentation=20(#2761)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update app.md for indentation --- docs/api/app.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/app.md b/docs/api/app.md index 93dae1bc64..198c83ce1d 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -205,7 +205,7 @@ func main() { app.Route("/test", func(api fiber.Router) { api.Get("/foo", handler).Name("foo") // /test/foo (name: test.foo) - api.Get("/bar", handler).Name("bar") // /test/bar (name: test.bar) + api.Get("/bar", handler).Name("bar") // /test/bar (name: test.bar) }, "test.") log.Fatal(app.Listen(":3000")) From c3fed55744190762959f6ae771ec3401eb0e3a5e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 13 Dec 2023 15:53:13 +0300 Subject: [PATCH 09/51] build(deps): bump github.com/google/uuid from 1.4.0 to 1.5.0 (#2762) Bumps [github.com/google/uuid](https://github.com/google/uuid) from 1.4.0 to 1.5.0. - [Release notes](https://github.com/google/uuid/releases) - [Changelog](https://github.com/google/uuid/blob/master/CHANGELOG.md) - [Commits](https://github.com/google/uuid/compare/v1.4.0...v1.5.0) --- updated-dependencies: - dependency-name: github.com/google/uuid dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- go.mod | 2 +- go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/go.mod b/go.mod index eac01a31fc..4112a1c4f1 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/gofiber/fiber/v2 go 1.20 require ( - github.com/google/uuid v1.4.0 + github.com/google/uuid v1.5.0 github.com/mattn/go-colorable v0.1.13 github.com/mattn/go-isatty v0.0.20 github.com/mattn/go-runewidth v0.0.15 diff --git a/go.sum b/go.sum index 56bcdc96b3..f000e1cacb 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/andybalholm/brotli v1.0.5 h1:8uQZIdzKmjc/iuPu7O2ioW48L81FgatrcpfFmiq/cCs= github.com/andybalholm/brotli v1.0.5/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= -github.com/google/uuid v1.4.0 h1:MtMxsa51/r9yyhkyLsVeVt0B+BGQZzpQiTQ4eHZ8bc4= -github.com/google/uuid v1.4.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= +github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/klauspost/compress v1.17.0 h1:Rnbp4K9EjcDuVuHtd0dgA4qNuv9yKDYKK1ulpJwgrqM= github.com/klauspost/compress v1.17.0/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= From b0925dc454b00f447ced2b51804eafed048ebf4c Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 16 Dec 2023 13:30:45 +0300 Subject: [PATCH 10/51] build(deps): bump github/codeql-action from 2 to 3 (#2763) Bumps [github/codeql-action](https://github.com/github/codeql-action) from 2 to 3. - [Release notes](https://github.com/github/codeql-action/releases) - [Changelog](https://github.com/github/codeql-action/blob/main/CHANGELOG.md) - [Commits](https://github.com/github/codeql-action/compare/v2...v3) --- updated-dependencies: - dependency-name: github/codeql-action dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/codeql-analysis.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index bedc27fe61..82036cc967 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -37,7 +37,7 @@ jobs: # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL - uses: github/codeql-action/init@v2 + uses: github/codeql-action/init@v3 # Override language selection by uncommenting this and choosing your languages with: languages: go @@ -45,7 +45,7 @@ jobs: # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild - uses: github/codeql-action/autobuild@v2 + uses: github/codeql-action/autobuild@v3 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl @@ -59,4 +59,4 @@ jobs: # make release - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v2 + uses: github/codeql-action/analyze@v3 From dc2d2ef52429887613c85e6177646a680c723fff Mon Sep 17 00:00:00 2001 From: Bruno Date: Mon, 18 Dec 2023 11:20:18 -0300 Subject: [PATCH 11/51] Changing default log output (#2730) changing default log output Closes #2729 --- docs/api/middleware/logger.md | 4 +-- middleware/logger/config.go | 4 +-- middleware/logger/logger.go | 53 -------------------------------- middleware/logger/logger_test.go | 2 +- 4 files changed, 5 insertions(+), 58 deletions(-) diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index 97c3c73872..d9e4fadad8 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -97,7 +97,7 @@ app.Use(logger.New(logger.Config{ | Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | | Done | `func(*fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` | | CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` | -| Format | `string` | Format defines the logging tags. | `[${time}] ${ip} ${status} - ${latency} ${method} ${path}\n` | +| Format | `string` | Format defines the logging tags. | `${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}` | | TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` | | TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` | | TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` | @@ -112,7 +112,7 @@ app.Use(logger.New(logger.Config{ var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path}\n", + Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/logger/config.go b/middleware/logger/config.go index 10b382b925..06a1a41846 100644 --- a/middleware/logger/config.go +++ b/middleware/logger/config.go @@ -28,7 +28,7 @@ type Config struct { // Format defines the logging tags // - // Optional. Default: [${time}] ${ip} ${status} - ${latency} ${method} ${path}\n + // Optional. Default: ${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} Format string // TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html @@ -86,7 +86,7 @@ type LogFunc func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (i var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path}\n", + Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/logger/logger.go b/middleware/logger/logger.go index f33f3562a3..b03617b2b3 100644 --- a/middleware/logger/logger.go +++ b/middleware/logger/logger.go @@ -85,9 +85,6 @@ func New(config ...Config) fiber.Handler { return c.Next() } - // Alias colors - colors := c.App().Config().ColorScheme - // Set error handler once once.Do(func() { // get longested possible path @@ -137,56 +134,6 @@ func New(config ...Config) fiber.Handler { // Get new buffer buf := bytebufferpool.Get() - // Default output when no custom Format or io.Writer is given - if cfg.Format == ConfigDefault.Format { - // Format error if exist - formatErr := "" - if cfg.enableColors { - if chainErr != nil { - formatErr = colors.Red + " | " + chainErr.Error() + colors.Reset - } - _, _ = buf.WriteString( //nolint:errcheck // This will never fail - fmt.Sprintf("%s |%s %3d %s| %13v | %15s |%s %-7s %s| %-"+errPaddingStr+"s %s\n", - timestamp.Load().(string), - statusColor(c.Response().StatusCode(), colors), c.Response().StatusCode(), colors.Reset, - data.Stop.Sub(data.Start), - c.IP(), - methodColor(c.Method(), colors), c.Method(), colors.Reset, - c.Path(), - formatErr, - ), - ) - } else { - if chainErr != nil { - formatErr = " | " + chainErr.Error() - } - _, _ = buf.WriteString( //nolint:errcheck // This will never fail - fmt.Sprintf("%s | %3d | %13v | %15s | %-7s | %-"+errPaddingStr+"s %s\n", - timestamp.Load().(string), - c.Response().StatusCode(), - data.Stop.Sub(data.Start), - c.IP(), - c.Method(), - c.Path(), - formatErr, - ), - ) - } - - // Write buffer to output - _, _ = cfg.Output.Write(buf.Bytes()) //nolint:errcheck // This will never fail - - if cfg.Done != nil { - cfg.Done(c, buf.Bytes()) - } - - // Put buffer back to pool - bytebufferpool.Put(buf) - - // End chain - return nil - } - var err error // Loop over template parts execute dynamic parts and add fixed parts to the buffer for i, logFunc := range logFunChain { diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index d563a5ccc6..6876a7219f 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -147,7 +147,7 @@ type fakeOutput int func (o *fakeOutput) Write([]byte) (int, error) { *o++ - return 0, errors.New("fake output") + return 0, nil } // go test -run Test_Logger_ErrorOutput_WithoutColor From 43fa236d991bfb090a695445275f13ceefff80a3 Mon Sep 17 00:00:00 2001 From: RW Date: Tue, 19 Dec 2023 13:27:10 +0100 Subject: [PATCH 12/51] Update hooks.md fix wrong hooks signature --- docs/guide/hooks.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/guide/hooks.md b/docs/guide/hooks.md index b001786535..357d59d33d 100644 --- a/docs/guide/hooks.md +++ b/docs/guide/hooks.md @@ -35,7 +35,7 @@ type OnMountHandler = func(*App) error OnRoute is a hook to execute user functions on each route registeration. Also you can get route properties by **route** parameter. ```go title="Signature" -func (app *App) OnRoute(handler ...OnRouteHandler) +func (h *Hooks) OnRoute(handler ...OnRouteHandler) ``` ## OnName @@ -47,7 +47,7 @@ OnName only works with naming routes, not groups. ::: ```go title="Signature" -func (app *App) OnName(handler ...OnNameHandler) +func (h *Hooks) OnName(handler ...OnNameHandler) ``` @@ -104,7 +104,7 @@ func main() { OnGroup is a hook to execute user functions on each group registeration. Also you can get group properties by **group** parameter. ```go title="Signature" -func (app *App) OnGroup(handler ...OnGroupHandler) +func (h *Hooks) OnGroup(handler ...OnGroupHandler) ``` ## OnGroupName @@ -116,7 +116,7 @@ OnGroupName only works with naming groups, not routes. ::: ```go title="Signature" -func (app *App) OnGroupName(handler ...OnGroupNameHandler) +func (h *Hooks) OnGroupName(handler ...OnGroupNameHandler) ``` ## OnListen @@ -124,7 +124,7 @@ func (app *App) OnGroupName(handler ...OnGroupNameHandler) OnListen is a hook to execute user functions on Listen, ListenTLS, Listener. ```go title="Signature" -func (app *App) OnListen(handler ...OnListenHandler) +func (h *Hooks) OnListen(handler ...OnListenHandler) ``` @@ -158,7 +158,7 @@ app.Listen(":5000") OnFork is a hook to execute user functions on Fork. ```go title="Signature" -func (app *App) OnFork(handler ...OnForkHandler) +func (h *Hooks) OnFork(handler ...OnForkHandler) ``` ## OnShutdown @@ -166,7 +166,7 @@ func (app *App) OnFork(handler ...OnForkHandler) OnShutdown is a hook to execute user functions after Shutdown. ```go title="Signature" -func (app *App) OnShutdown(handler ...OnShutdownHandler) +func (h *Hooks) OnShutdown(handler ...OnShutdownHandler) ``` ## OnMount From 1fac52a42af3f9a4981de71e27b4edd6090dac31 Mon Sep 17 00:00:00 2001 From: Muhammad Kholid B Date: Fri, 22 Dec 2023 20:48:37 +0700 Subject: [PATCH 13/51] =?UTF-8?q?=F0=9F=A9=B9=20Fix:=20CORS=20middleware?= =?UTF-8?q?=20should=20use=20the=20defined=20AllowedOriginsFunc=20config?= =?UTF-8?q?=20when=20AllowedOrigins=20is=20empty=20(#2771)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/cors/cors.go | 7 +- middleware/cors/cors_test.go | 201 ++++++++++++++++++++++++++++++++++- 2 files changed, 202 insertions(+), 6 deletions(-) diff --git a/middleware/cors/cors.go b/middleware/cors/cors.go index c347e43525..ebc1c6b1cb 100644 --- a/middleware/cors/cors.go +++ b/middleware/cors/cors.go @@ -94,13 +94,14 @@ func New(config ...Config) fiber.Handler { if cfg.AllowMethods == "" { cfg.AllowMethods = ConfigDefault.AllowMethods } - if cfg.AllowOrigins == "" { + // When none of the AllowOrigins or AllowOriginsFunc config was defined, set the default AllowOrigins value with "*" + if cfg.AllowOrigins == "" && cfg.AllowOriginsFunc == nil { cfg.AllowOrigins = ConfigDefault.AllowOrigins } } // Warning logs if both AllowOrigins and AllowOriginsFunc are set - if cfg.AllowOrigins != ConfigDefault.AllowOrigins && cfg.AllowOriginsFunc != nil { + if cfg.AllowOrigins != "" && cfg.AllowOriginsFunc != nil { log.Warn("[CORS] Both 'AllowOrigins' and 'AllowOriginsFunc' have been defined.") } @@ -145,7 +146,7 @@ func New(config ...Config) fiber.Handler { // Run AllowOriginsFunc if the logic for // handling the value in 'AllowOrigins' does // not result in allowOrigin being set. - if (allowOrigin == "" || allowOrigin == ConfigDefault.AllowOrigins) && cfg.AllowOriginsFunc != nil { + if allowOrigin == "" && cfg.AllowOriginsFunc != nil { if cfg.AllowOriginsFunc(origin) { allowOrigin = origin } diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 692a24bfcc..22fef8442b 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -331,9 +331,9 @@ func Test_CORS_AllowOriginsFunc(t *testing.T) { // Perform request handler(ctx) - // Allow-Origin header should be "*" because http://google.com does not satisfy 'strings.Contains(origin, "example-2")' - // and AllowOrigins has not been set so the default "*" is used - utils.AssertEqual(t, "*", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) + // Allow-Origin header should be empty because http://google.com does not satisfy 'strings.Contains(origin, "example-2")' + // and AllowOrigins has not been set + utils.AssertEqual(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) ctx.Request.Reset() ctx.Response.Reset() @@ -348,3 +348,198 @@ func Test_CORS_AllowOriginsFunc(t *testing.T) { // Allow-Origin header should be "http://example-2.com" utils.AssertEqual(t, "http://example-2.com", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) } + +func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { + testCases := []struct { + Name string + Config Config + RequestOrigin string + ResponseOrigin string + }{ + { + Name: "AllowOriginsDefined/AllowOriginsFuncUndefined/OriginAllowed", + Config: Config{ + AllowOrigins: "http://aaa.com", + AllowOriginsFunc: nil, + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + }, + { + Name: "AllowOriginsDefined/AllowOriginsFuncUndefined/OriginNotAllowed", + Config: Config{ + AllowOrigins: "http://aaa.com", + AllowOriginsFunc: nil, + }, + RequestOrigin: "http://bbb.com", + ResponseOrigin: "", + }, + { + Name: "AllowOriginsDefined/AllowOriginsFuncReturnsTrue/OriginAllowed", + Config: Config{ + AllowOrigins: "http://aaa.com", + AllowOriginsFunc: func(origin string) bool { + return true + }, + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + }, + { + Name: "AllowOriginsDefined/AllowOriginsFuncReturnsTrue/OriginNotAllowed", + Config: Config{ + AllowOrigins: "http://aaa.com", + AllowOriginsFunc: func(origin string) bool { + return true + }, + }, + RequestOrigin: "http://bbb.com", + ResponseOrigin: "http://bbb.com", + }, + { + Name: "AllowOriginsDefined/AllowOriginsFuncReturnsFalse/OriginAllowed", + Config: Config{ + AllowOrigins: "http://aaa.com", + AllowOriginsFunc: func(origin string) bool { + return false + }, + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + }, + { + Name: "AllowOriginsDefined/AllowOriginsFuncReturnsFalse/OriginNotAllowed", + Config: Config{ + AllowOrigins: "http://aaa.com", + AllowOriginsFunc: func(origin string) bool { + return false + }, + }, + RequestOrigin: "http://bbb.com", + ResponseOrigin: "", + }, + { + Name: "AllowOriginsEmpty/AllowOriginsFuncUndefined/OriginAllowed", + Config: Config{ + AllowOrigins: "", + AllowOriginsFunc: nil, + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "*", + }, + { + Name: "AllowOriginsEmpty/AllowOriginsFuncReturnsTrue/OriginAllowed", + Config: Config{ + AllowOrigins: "", + AllowOriginsFunc: func(origin string) bool { + return true + }, + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + }, + { + Name: "AllowOriginsEmpty/AllowOriginsFuncReturnsFalse/OriginNotAllowed", + Config: Config{ + AllowOrigins: "", + AllowOriginsFunc: func(origin string) bool { + return false + }, + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "", + }, + } + + for _, tc := range testCases { + t.Run(tc.Name, func(t *testing.T) { + app := fiber.New() + app.Use("/", New(tc.Config)) + + handler := app.Handler() + + ctx := &fasthttp.RequestCtx{} + ctx.Request.SetRequestURI("/") + ctx.Request.Header.SetMethod(fiber.MethodOptions) + ctx.Request.Header.Set(fiber.HeaderOrigin, tc.RequestOrigin) + + handler(ctx) + + utils.AssertEqual(t, tc.ResponseOrigin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) + }) + } +} + +// The fix for issue #2422 +func Test_CORS_AllowCredetials(t *testing.T) { + testCases := []struct { + Name string + Config Config + RequestOrigin string + ResponseOrigin string + }{ + { + Name: "AllowOriginsFuncDefined", + Config: Config{ + AllowCredentials: true, + AllowOriginsFunc: func(origin string) bool { + return true + }, + }, + RequestOrigin: "http://aaa.com", + // The AllowOriginsFunc config was defined, should use the real origin of the function + ResponseOrigin: "http://aaa.com", + }, + { + Name: "AllowOriginsFuncNotDefined", + Config: Config{ + AllowCredentials: true, + }, + RequestOrigin: "http://aaa.com", + // None of the AllowOrigins or AllowOriginsFunc config was defined, should use the default origin of "*" + // which will cause the CORS error in the client: + // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' + // when the request's credentials mode is 'include'. + ResponseOrigin: "*", + }, + { + Name: "AllowOriginsDefined", + Config: Config{ + AllowCredentials: true, + AllowOrigins: "http://aaa.com", + }, + RequestOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + }, + { + Name: "AllowOriginsDefined/UnallowedOrigin", + Config: Config{ + AllowCredentials: true, + AllowOrigins: "http://aaa.com", + }, + RequestOrigin: "http://bbb.com", + ResponseOrigin: "", + }, + } + + for _, tc := range testCases { + t.Run(tc.Name, func(t *testing.T) { + app := fiber.New() + app.Use("/", New(tc.Config)) + + handler := app.Handler() + + ctx := &fasthttp.RequestCtx{} + ctx.Request.SetRequestURI("/") + ctx.Request.Header.SetMethod(fiber.MethodOptions) + ctx.Request.Header.Set(fiber.HeaderOrigin, tc.RequestOrigin) + + handler(ctx) + + if tc.Config.AllowCredentials { + utils.AssertEqual(t, "true", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) + } + utils.AssertEqual(t, tc.ResponseOrigin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) + }) + } +} From c49faf9a8ae63a09fdec77b2b17972c447a92116 Mon Sep 17 00:00:00 2001 From: RW Date: Fri, 22 Dec 2023 14:49:58 +0100 Subject: [PATCH 14/51] =?UTF-8?q?=F0=9F=90=9B=20[Bug]:=20Adaptator=20+=20o?= =?UTF-8?q?telfiber=20issue=20#2641=20(#2772)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- middleware/adaptor/adaptor.go | 2 ++ middleware/adaptor/adaptor_test.go | 6 ++++++ 2 files changed, 8 insertions(+) diff --git a/middleware/adaptor/adaptor.go b/middleware/adaptor/adaptor.go index db2149d921..8bd6f3fe00 100644 --- a/middleware/adaptor/adaptor.go +++ b/middleware/adaptor/adaptor.go @@ -76,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) @@ -128,6 +129,7 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc { 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) diff --git a/middleware/adaptor/adaptor_test.go b/middleware/adaptor/adaptor_test.go index 6e03b05a2d..dc52704760 100644 --- a/middleware/adaptor/adaptor_test.go +++ b/middleware/adaptor/adaptor_test.go @@ -116,6 +116,7 @@ var ( ) func Test_HTTPMiddleware(t *testing.T) { + const expectedHost = "foobar.com" tests := []struct { name string url string @@ -148,6 +149,7 @@ func Test_HTTPMiddleware(t *testing.T) { w.WriteHeader(http.StatusMethodNotAllowed) return } + r = r.WithContext(context.WithValue(r.Context(), TestContextKey, "okay")) r = r.WithContext(context.WithValue(r.Context(), TestContextSecondKey, "not_okay")) r = r.WithContext(context.WithValue(r.Context(), TestContextSecondKey, "okay")) @@ -180,6 +182,7 @@ func Test_HTTPMiddleware(t *testing.T) { for _, tt := range tests { req, err := http.NewRequestWithContext(context.Background(), tt.method, tt.url, nil) + req.Host = expectedHost utils.AssertEqual(t, nil, err) resp, err := app.Test(req) @@ -188,6 +191,7 @@ func Test_HTTPMiddleware(t *testing.T) { } req, err := http.NewRequestWithContext(context.Background(), fiber.MethodPost, "/", nil) + req.Host = expectedHost utils.AssertEqual(t, nil, err) resp, err := app.Test(req) @@ -239,6 +243,8 @@ func testFiberToHandlerFunc(t *testing.T, checkDefaultPort bool, app ...*fiber.A utils.AssertEqual(t, expectedRequestURI, string(c.Context().RequestURI()), "RequestURI") utils.AssertEqual(t, expectedContentLength, c.Context().Request.Header.ContentLength(), "ContentLength") utils.AssertEqual(t, expectedHost, c.Hostname(), "Host") + utils.AssertEqual(t, expectedHost, string(c.Request().Header.Host()), "Host") + utils.AssertEqual(t, "http://"+expectedHost, c.BaseURL(), "BaseURL") utils.AssertEqual(t, expectedRemoteAddr, c.Context().RemoteAddr().String(), "RemoteAddr") body := string(c.Body()) From d6c88764ebaf0e48b98eaa1069168a9e00d6aa98 Mon Sep 17 00:00:00 2001 From: gilwo Date: Fri, 22 Dec 2023 17:18:04 +0200 Subject: [PATCH 15/51] =?UTF-8?q?=F0=9F=A9=B9=F0=9F=9A=A8=20-=20fix=20for?= =?UTF-8?q?=20redirect=20with=20query=20params=20(#2748)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * redirect with query params did not work, fix it and add test for it * redirect middleware - fix test typo --- middleware/redirect/redirect.go | 6 +++++- middleware/redirect/redirect_test.go | 12 ++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/middleware/redirect/redirect.go b/middleware/redirect/redirect.go index 7af21320fe..2818142e54 100644 --- a/middleware/redirect/redirect.go +++ b/middleware/redirect/redirect.go @@ -30,7 +30,11 @@ func New(config ...Config) fiber.Handler { for k, v := range cfg.rulesRegex { replacer := captureTokens(k, c.Path()) if replacer != nil { - return c.Redirect(replacer.Replace(v), cfg.StatusCode) + queryString := string(c.Context().QueryArgs().QueryString()) + if queryString != "" { + queryString = "?" + queryString + } + return c.Redirect(replacer.Replace(v)+queryString, cfg.StatusCode) } } return c.Next() diff --git a/middleware/redirect/redirect_test.go b/middleware/redirect/redirect_test.go index b6323ab54b..61fc00a11a 100644 --- a/middleware/redirect/redirect_test.go +++ b/middleware/redirect/redirect_test.go @@ -44,6 +44,12 @@ func Test_Redirect(t *testing.T) { }, StatusCode: fiber.StatusMovedPermanently, })) + app.Use(New(Config{ + Rules: map[string]string{ + "/params": "/with_params", + }, + StatusCode: fiber.StatusMovedPermanently, + })) app.Get("/api/*", func(c *fiber.Ctx) error { return c.SendString("API") @@ -104,6 +110,12 @@ func Test_Redirect(t *testing.T) { url: "/api/test", statusCode: fiber.StatusOK, }, + { + name: "redirect with query params", + url: "/params?query=abc", + redirectTo: "/with_params?query=abc", + statusCode: fiber.StatusMovedPermanently, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { From 38eb4bd238dda7c8b1eedd628267b5bb5263a6d4 Mon Sep 17 00:00:00 2001 From: RW Date: Sat, 23 Dec 2023 08:31:58 +0100 Subject: [PATCH 16/51] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20logger/middleware=20?= =?UTF-8?q?colorize=20logger=20error=20message=20#2593=20(#2773)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/api/middleware/logger.md | 30 +++++++++++++++--------------- middleware/logger/config.go | 4 ++-- middleware/logger/tags.go | 4 ++++ 3 files changed, 21 insertions(+), 17 deletions(-) diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index d9e4fadad8..0a23441aa3 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -92,27 +92,27 @@ app.Use(logger.New(logger.Config{ ### Config -| Property | Type | Description | Default | -|:-----------------|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------|:-------------------------------------------------------| -| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | -| Done | `func(*fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` | -| CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` | -| Format | `string` | Format defines the logging tags. | `${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}` | -| TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` | -| TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` | -| TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` | -| Output | `io.Writer` | Output is a writer where logs are written. | `os.Stdout` | -| DisableColors | `bool` | DisableColors defines if the logs output should be colorized. | `false` | -| enableColors | `bool` | Internal field for enabling colors in the log output. (This is not a user-configurable field) | - | -| enableLatency | `bool` | Internal field for enabling latency measurement in logs. (This is not a user-configurable field) | - | -| timeZoneLocation | `*time.Location` | Internal field for the time zone location. (This is not a user-configurable field) | - | +| Property | Type | Description | Default | +|:-----------------|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------|:-------------------------| +| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | +| Done | `func(*fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` | +| CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` | +| Format | `string` | Format defines the logging tags. | `${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n` | +| TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` | +| TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` | +| TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` | +| Output | `io.Writer` | Output is a writer where logs are written. | `os.Stdout` | +| DisableColors | `bool` | DisableColors defines if the logs output should be colorized. | `false` | +| enableColors | `bool` | Internal field for enabling colors in the log output. (This is not a user-configurable field) | - | +| enableLatency | `bool` | Internal field for enabling latency measurement in logs. (This is not a user-configurable field) | - | +| timeZoneLocation | `*time.Location` | Internal field for the time zone location. (This is not a user-configurable field) | - | ## Default Config ```go var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}", + Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/logger/config.go b/middleware/logger/config.go index 06a1a41846..b84714cad5 100644 --- a/middleware/logger/config.go +++ b/middleware/logger/config.go @@ -28,7 +28,7 @@ type Config struct { // Format defines the logging tags // - // Optional. Default: ${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} + // Optional. Default: ${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n Format string // TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html @@ -86,7 +86,7 @@ type LogFunc func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (i var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path}\n", + Format: "${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/logger/tags.go b/middleware/logger/tags.go index 67ccbb83a2..9a10279eca 100644 --- a/middleware/logger/tags.go +++ b/middleware/logger/tags.go @@ -139,6 +139,10 @@ func createTagMap(cfg *Config) map[string]LogFunc { }, TagError: func(output Buffer, c *fiber.Ctx, data *Data, extraParam string) (int, error) { if data.ChainErr != nil { + if cfg.enableColors { + colors := c.App().Config().ColorScheme + return output.WriteString(fmt.Sprintf("%s%s%s", colors.Red, data.ChainErr.Error(), colors.Reset)) + } return output.WriteString(data.ChainErr.Error()) } return output.WriteString("-") From 6249bc48bcc9359e48cd5fb826a00ba485def6f0 Mon Sep 17 00:00:00 2001 From: Lucas Lemos Date: Wed, 3 Jan 2024 14:13:58 -0300 Subject: [PATCH 17/51] :sparkles: feat: add liveness and readiness checks (#2509) * :sparkles: feat: add liveness and readiness checkers * :memo: docs: add docs for liveness and readiness * :sparkles: feat: add options method for probe checkers * :white_check_mark: tests: add tests for liveness and readiness * :recycle: refactor: change default endpoint values * :recycle: refactor: change default value for liveness endpoint * :memo: docs: add return status for liveness and readiness probes * :recycle: refactor: change probechecker to middleware * :memo: docs: move docs to middleware session * :recycle: refactor: apply gofumpt formatting * :recycle: refactor: remove unused parameter * split config and apply a review * apply reviews and add testcases * add benchmark * cleanup * rename middleware * fix linter * Update docs and config values * Revert change to IsReady * Updates based on code review * Update docs to match other middlewares --------- Co-authored-by: Muhammed Efe Cetin Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Co-authored-by: Juan Calderon-Perez --- docs/api/app.md | 2 +- docs/api/middleware/healthcheck.md | 105 ++++++++++++++++++ middleware/healthcheck/config.go | 84 +++++++++++++++ middleware/healthcheck/healthcheck.go | 52 +++++++++ middleware/healthcheck/healthcheck_test.go | 117 +++++++++++++++++++++ 5 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 docs/api/middleware/healthcheck.md create mode 100644 middleware/healthcheck/config.go create mode 100644 middleware/healthcheck/healthcheck.go create mode 100644 middleware/healthcheck/healthcheck_test.go diff --git a/docs/api/app.md b/docs/api/app.md index 198c83ce1d..cb38f7051f 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -654,4 +654,4 @@ Hooks is a method to return [hooks](../guide/hooks.md) property. ```go title="Signature" func (app *App) Hooks() *Hooks -``` +``` \ No newline at end of file diff --git a/docs/api/middleware/healthcheck.md b/docs/api/middleware/healthcheck.md new file mode 100644 index 0000000000..3f2bb6c5fb --- /dev/null +++ b/docs/api/middleware/healthcheck.md @@ -0,0 +1,105 @@ +--- +id: healthcheck +title: healthcheck +--- + +Liveness and readiness probes middleware for [Fiber](https://github.com/gofiber/fiber) that provides two endpoints for checking the liveness and readiness state of HTTP applications. + +## Overview + +- **Liveness Probe**: Checks if the server is up and running. + - **Default Endpoint**: `/livez` + - **Behavior**: By default returns `true` immediately when the server is operational. + +- **Readiness Probe**: Assesses if the application is ready to handle requests. + - **Default Endpoint**: `/readyz` + - **Behavior**: By default returns `true` immediately when the server is operational. + +- **HTTP Status Codes**: + - `200 OK`: Returned when the checker function evaluates to `true`. + - `503 Service Unavailable`: Returned when the checker function evaluates to `false`. + +## Signatures + +```go +func New(config Config) fiber.Handler +``` + +## Examples + +Import the middleware package that is part of the Fiber web framework +```go +import ( + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/healthcheck" +) +``` + +After you initiate your Fiber app, you can use the following possibilities: + +```go +// Provide a minimal config +app.Use(healthcheck.New()) + +// Or extend your config for customization +app.Use(healthcheck.New(healthcheck.Config{ + LivenessProbe: func(c *fiber.Ctx) bool { + return true + }, + LivenessEndpoint: "/live", + ReadinessProbe: func(c *fiber.Ctx) bool { + return serviceA.Ready() && serviceB.Ready() && ... + }, + ReadinessEndpoint: "/ready", +})) +``` + +## Config + +```go +type Config struct { + // Next defines a function to skip this middleware when returned true. + // + // Optional. Default: nil + Next func(c *fiber.Ctx) bool + + // Function used for checking the liveness of the application. Returns true if the application + // is running and false if it is not. The liveness probe is typically used to indicate if + // the application is in a state where it can handle requests (e.g., the server is up and running). + // + // Optional. Default: func(c *fiber.Ctx) bool { return true } + LivenessProbe HealthChecker + + // HTTP endpoint at which the liveness probe will be available. + // + // Optional. Default: "/livez" + LivenessEndpoint string + + // Function used for checking the readiness of the application. Returns true if the application + // is ready to process requests and false otherwise. The readiness probe typically checks if all necessary + // services, databases, and other dependencies are available for the application to function correctly. + // + // Optional. Default: func(c *fiber.Ctx) bool { return true } + ReadinessProbe HealthChecker + + // HTTP endpoint at which the readiness probe will be available. + // Optional. Default: "/readyz" + ReadinessEndpoint string +} +``` + +## Default Config + +The default configuration used by this middleware is defined as follows: +```go +func defaultLivenessProbe(*fiber.Ctx) bool { return true } + +func defaultReadinessProbe(*fiber.Ctx) bool { return true } + +var ConfigDefault = Config{ + LivenessProbe: defaultLivenessProbe, + ReadinessProbe: defaultReadinessProbe, + LivenessEndpoint: "/livez", + ReadinessEndpoint: "/readyz", +} +``` \ No newline at end of file diff --git a/middleware/healthcheck/config.go b/middleware/healthcheck/config.go new file mode 100644 index 0000000000..d4e5fac1b0 --- /dev/null +++ b/middleware/healthcheck/config.go @@ -0,0 +1,84 @@ +package healthcheck + +import ( + "github.com/gofiber/fiber/v2" +) + +// Config defines the configuration options for the healthcheck middleware. +type Config struct { + // Next defines a function to skip this middleware when returned true. + // + // Optional. Default: nil + Next func(c *fiber.Ctx) bool + + // Function used for checking the liveness of the application. Returns true if the application + // is running and false if it is not. The liveness probe is typically used to indicate if + // the application is in a state where it can handle requests (e.g., the server is up and running). + // + // Optional. Default: func(c *fiber.Ctx) bool { return true } + LivenessProbe HealthChecker + + // HTTP endpoint at which the liveness probe will be available. + // + // Optional. Default: "/livez" + LivenessEndpoint string + + // Function used for checking the readiness of the application. Returns true if the application + // is ready to process requests and false otherwise. The readiness probe typically checks if all necessary + // services, databases, and other dependencies are available for the application to function correctly. + // + // Optional. Default: func(c *fiber.Ctx) bool { return true } + ReadinessProbe HealthChecker + + // HTTP endpoint at which the readiness probe will be available. + // Optional. Default: "/readyz" + ReadinessEndpoint string +} + +const ( + DefaultLivenessEndpoint = "/livez" + DefaultReadinessEndpoint = "/readyz" +) + +func defaultLivenessProbe(*fiber.Ctx) bool { return true } + +func defaultReadinessProbe(*fiber.Ctx) bool { return true } + +// ConfigDefault is the default config +var ConfigDefault = Config{ + LivenessProbe: defaultLivenessProbe, + ReadinessProbe: defaultReadinessProbe, + LivenessEndpoint: DefaultLivenessEndpoint, + ReadinessEndpoint: DefaultReadinessEndpoint, +} + +// defaultConfig returns a default config for the healthcheck middleware. +func defaultConfig(config ...Config) Config { + if len(config) < 1 { + return ConfigDefault + } + + cfg := config[0] + + if cfg.Next == nil { + cfg.Next = ConfigDefault.Next + } + + if cfg.LivenessProbe == nil { + cfg.LivenessProbe = defaultLivenessProbe + } + + if cfg.ReadinessProbe == nil { + cfg.ReadinessProbe = defaultReadinessProbe + } + + if cfg.LivenessEndpoint == "" { + cfg.LivenessEndpoint = DefaultLivenessEndpoint + } + + if cfg.ReadinessEndpoint == "" { + cfg.ReadinessEndpoint = DefaultReadinessEndpoint + } + + return cfg +} diff --git a/middleware/healthcheck/healthcheck.go b/middleware/healthcheck/healthcheck.go new file mode 100644 index 0000000000..14ff33430c --- /dev/null +++ b/middleware/healthcheck/healthcheck.go @@ -0,0 +1,52 @@ +package healthcheck + +import ( + "github.com/gofiber/fiber/v2" +) + +// HealthChecker defines a function to check liveness or readiness of the application +type HealthChecker func(*fiber.Ctx) bool + +// ProbeCheckerHandler defines a function that returns a ProbeChecker +type HealthCheckerHandler func(HealthChecker) fiber.Handler + +func healthCheckerHandler(checker HealthChecker) fiber.Handler { + return func(c *fiber.Ctx) error { + if checker == nil { + return c.Next() + } + + if checker(c) { + return c.SendStatus(fiber.StatusOK) + } + + return c.SendStatus(fiber.StatusServiceUnavailable) + } +} + +func New(config ...Config) fiber.Handler { + cfg := defaultConfig(config...) + + isLiveHandler := healthCheckerHandler(cfg.LivenessProbe) + isReadyHandler := healthCheckerHandler(cfg.ReadinessProbe) + + return func(c *fiber.Ctx) error { + // Don't execute middleware if Next returns true + if cfg.Next != nil && cfg.Next(c) { + return c.Next() + } + + if c.Method() != fiber.MethodGet { + return c.Next() + } + + switch c.Path() { + case cfg.ReadinessEndpoint: + return isReadyHandler(c) + case cfg.LivenessEndpoint: + return isLiveHandler(c) + } + + return c.Next() + } +} diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go new file mode 100644 index 0000000000..df0165f158 --- /dev/null +++ b/middleware/healthcheck/healthcheck_test.go @@ -0,0 +1,117 @@ +package healthcheck + +import ( + "net/http/httptest" + "testing" + "time" + + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/utils" + "github.com/valyala/fasthttp" +) + +func Test_HealthCheck_Default(t *testing.T) { + t.Parallel() + + app := fiber.New() + app.Use(New()) + + req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/readyz", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + + req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) +} + +func Test_HealthCheck_Custom(t *testing.T) { + t.Parallel() + + app := fiber.New() + + c1 := make(chan struct{}, 1) + go func() { + time.Sleep(1 * time.Second) + c1 <- struct{}{} + }() + + app.Use(New(Config{ + LivenessProbe: func(c *fiber.Ctx) bool { + return true + }, + LivenessEndpoint: "/live", + ReadinessProbe: func(c *fiber.Ctx) bool { + select { + case <-c1: + return true + default: + return false + } + }, + ReadinessEndpoint: "/ready", + })) + + // Live should return 200 with GET request + req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/live", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + + // Live should return 404 with POST request + req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) + + // Ready should return 404 with POST request + req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) + + // Ready should return 503 with GET request before the channel is closed + req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusServiceUnavailable, req.StatusCode) + + time.Sleep(1 * time.Second) + + // Ready should return 200 with GET request after the channel is closed + req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) +} + +func Test_HealthCheck_Next(t *testing.T) { + t.Parallel() + + app := fiber.New() + + app.Use(New(Config{ + Next: func(c *fiber.Ctx) bool { + return true + }, + })) + + req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) +} + +func Benchmark_HealthCheck(b *testing.B) { + app := fiber.New() + + app.Use(New()) + + h := app.Handler() + fctx := &fasthttp.RequestCtx{} + fctx.Request.Header.SetMethod(fiber.MethodGet) + fctx.Request.SetRequestURI("/livez") + + b.ReportAllocs() + b.ResetTimer() + + for i := 0; i < b.N; i++ { + h(fctx) + } + + utils.AssertEqual(b, fiber.StatusOK, fctx.Response.Header.StatusCode()) +} From 89f551becc0499931902e38b4249b8f2a4b313c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Fri, 5 Jan 2024 14:02:59 +0100 Subject: [PATCH 18/51] prepare release v2.52.0 - add more Parser tests --- app.go | 2 +- ctx_test.go | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+), 1 deletion(-) diff --git a/app.go b/app.go index 47a01dd08a..2ce88704c5 100644 --- a/app.go +++ b/app.go @@ -30,7 +30,7 @@ import ( ) // Version of current fiber package -const Version = "2.51.0" +const Version = "2.52.0" // Handler defines a function to serve HTTP requests. type Handler = func(*Ctx) error diff --git a/ctx_test.go b/ctx_test.go index ea9dfa8485..a278d2f250 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1372,6 +1372,100 @@ func Benchmark_Ctx_Fresh_WithNoCache(b *testing.B) { } } +// go test -run Test_Ctx_Parsers -v +func Test_Ctx_Parsers(t *testing.T) { + t.Parallel() + // setup + app := New() + + type TestStruct struct { + Name string + Class int + NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" reqHeader:"name2"` + ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" reqHeader:"class2"` + } + + withValues := func(t *testing.T, actionFn func(c *Ctx, testStruct *TestStruct) error) { + t.Helper() + c := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(c) + testStruct := new(TestStruct) + + utils.AssertEqual(t, nil, actionFn(c, testStruct)) + utils.AssertEqual(t, "foo", testStruct.Name) + utils.AssertEqual(t, 111, testStruct.Class) + utils.AssertEqual(t, "bar", testStruct.NameWithDefault) + utils.AssertEqual(t, 222, testStruct.ClassWithDefault) + } + + t.Run("BodyParser:xml", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.Request().Header.SetContentType(MIMEApplicationXML) + c.Request().SetBody([]byte(`foo111bar222`)) + return c.BodyParser(testStruct) + }) + }) + t.Run("BodyParser:form", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.Request().Header.SetContentType(MIMEApplicationForm) + c.Request().SetBody([]byte(`name=foo&class=111&name2=bar&class2=222`)) + return c.BodyParser(testStruct) + }) + }) + t.Run("BodyParser:json", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.Request().Header.SetContentType(MIMEApplicationJSON) + c.Request().SetBody([]byte(`{"name":"foo","class":111,"name2":"bar","class2":222}`)) + return c.BodyParser(testStruct) + }) + }) + t.Run("BodyParser:multiform", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + body := []byte("--b\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nfoo\r\n--b\r\nContent-Disposition: form-data; name=\"class\"\r\n\r\n111\r\n--b\r\nContent-Disposition: form-data; name=\"name2\"\r\n\r\nbar\r\n--b\r\nContent-Disposition: form-data; name=\"class2\"\r\n\r\n222\r\n--b--") + c.Request().SetBody(body) + c.Request().Header.SetContentType(MIMEMultipartForm + `;boundary="b"`) + c.Request().Header.SetContentLength(len(body)) + return c.BodyParser(testStruct) + }) + }) + t.Run("CookieParser", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.Request().Header.Set("Cookie", "name=foo;name2=bar;class=111;class2=222") + return c.CookieParser(testStruct) + }) + }) + t.Run("QueryParser", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.Request().URI().SetQueryString("name=foo&name2=bar&class=111&class2=222") + return c.QueryParser(testStruct) + }) + }) + t.Run("ParamsParser", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.route = &Route{Params: []string{"name", "name2", "class", "class2"}} + c.values = [30]string{"foo", "bar", "111", "222"} + return c.ParamsParser(testStruct) + }) + }) + t.Run("ReqHeaderParser", func(t *testing.T) { + t.Parallel() + withValues(t, func(c *Ctx, testStruct *TestStruct) error { + c.Request().Header.Add("name", "foo") + c.Request().Header.Add("name2", "bar") + c.Request().Header.Add("class", "111") + c.Request().Header.Add("class2", "222") + return c.ReqHeaderParser(testStruct) + }) + }) +} + // go test -run Test_Ctx_Get func Test_Ctx_Get(t *testing.T) { t.Parallel() From 476e1ed9fe3e0338e37c7ba36901e36bea1f298f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Fri, 5 Jan 2024 14:36:18 +0100 Subject: [PATCH 19/51] fix healthcheck.md --- docs/api/middleware/healthcheck.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/docs/api/middleware/healthcheck.md b/docs/api/middleware/healthcheck.md index 3f2bb6c5fb..641c236b1b 100644 --- a/docs/api/middleware/healthcheck.md +++ b/docs/api/middleware/healthcheck.md @@ -1,8 +1,9 @@ --- id: healthcheck -title: healthcheck --- +# Health Check + Liveness and readiness probes middleware for [Fiber](https://github.com/gofiber/fiber) that provides two endpoints for checking the liveness and readiness state of HTTP applications. ## Overview @@ -27,7 +28,7 @@ func New(config Config) fiber.Handler ## Examples -Import the middleware package that is part of the Fiber web framework +Import the middleware package that is part of the [Fiber](https://github.com/gofiber/fiber) web framework ```go import ( "github.com/gofiber/fiber/v2" @@ -35,7 +36,7 @@ import ( ) ``` -After you initiate your Fiber app, you can use the following possibilities: +After you initiate your [Fiber](https://github.com/gofiber/fiber) app, you can use the following possibilities: ```go // Provide a minimal config @@ -102,4 +103,4 @@ var ConfigDefault = Config{ LivenessEndpoint: "/livez", ReadinessEndpoint: "/readyz", } -``` \ No newline at end of file +``` From 2e66937b4e9f2d313dbbc3c0f5c21f28fc60119f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Sat, 6 Jan 2024 17:36:42 +0100 Subject: [PATCH 20/51] configure workflows for V2 branch --- .../ISSUE_TEMPLATE/feature-request-v3.yaml | 74 ------------------- .../ISSUE_TEMPLATE/maintenance-task-v3.yaml | 54 -------------- .github/PULL_REQUEST_TEMPLATE/v3-changes.md | 44 ----------- .github/pull_request_template.md | 2 - .github/release-drafter.yml | 2 + .github/scripts/sync_docs.sh | 19 ++--- .github/workflows/benchmark.yml | 3 +- .github/workflows/codeql-analysis.yml | 3 +- .github/workflows/linter.yml | 3 +- .github/workflows/release-drafter.yml | 3 +- .github/workflows/sync-docs.yml | 11 ++- .github/workflows/test.yml | 3 +- .github/workflows/vulncheck.yml | 3 +- 13 files changed, 23 insertions(+), 201 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/feature-request-v3.yaml delete mode 100644 .github/ISSUE_TEMPLATE/maintenance-task-v3.yaml delete mode 100644 .github/PULL_REQUEST_TEMPLATE/v3-changes.md diff --git a/.github/ISSUE_TEMPLATE/feature-request-v3.yaml b/.github/ISSUE_TEMPLATE/feature-request-v3.yaml deleted file mode 100644 index c7551b6d0e..0000000000 --- a/.github/ISSUE_TEMPLATE/feature-request-v3.yaml +++ /dev/null @@ -1,74 +0,0 @@ -name: "📝 Feature Proposal for v3" -title: "📝 [v3 Proposal]: " -description: Propose a feature or improvement for Fiber v3. -labels: ["📝 Proposal", "v3"] - -body: - - type: markdown - id: notice - attributes: - value: | - ### Notice - - For questions, join our [Discord server](https://gofiber.io/discord). - - Please write in clear, understandable English. - - Ensure your proposal aligns with Express design principles and HTTP RFC standards. - - Describe features expected to remain stable and not require changes in the foreseeable future. - - - type: textarea - id: description - attributes: - label: "Feature Proposal Description" - description: "A clear and detailed description of the feature you are proposing for Fiber v3. How should it work, and what API endpoints and methods would it involve?" - placeholder: "Describe your feature proposal clearly and in detail, including API endpoints and methods." - validations: - required: true - - - type: textarea - id: express-alignment - attributes: - label: "Alignment with Express API" - description: "Explain how your proposal aligns with the design and API of Express.js. Provide comparative examples if possible." - placeholder: "Outline how the feature aligns with Express.js design principles and API standards." - validations: - required: true - - - type: textarea - id: standards-compliance - attributes: - label: "HTTP RFC Standards Compliance" - description: "Confirm that the feature complies with HTTP RFC standards, and describe any relevant aspects." - placeholder: "Detail how the feature adheres to HTTP RFC standards." - validations: - required: true - - - type: textarea - id: stability - attributes: - label: "API Stability" - description: "Discuss the expected stability of the feature and its API. How do you ensure that it will not require changes or deprecations in the near future?" - placeholder: "Describe measures taken to ensure the feature's API stability over time." - validations: - required: true - - - type: textarea - id: examples - attributes: - label: "Feature Examples" - description: "Provide concrete examples and code snippets to illustrate how the proposed feature should function." - placeholder: "Share code snippets that exemplify the proposed feature and its usage." - render: go - validations: - required: true - - - type: checkboxes - id: terms - attributes: - label: "Checklist:" - description: "By submitting this issue, you confirm that:" - options: - - label: "I agree to follow Fiber's [Code of Conduct](https://github.com/gofiber/fiber/blob/master/.github/CODE_OF_CONDUCT.md)." - required: true - - label: "I have searched for existing issues that describe my proposal before opening this one." - required: true - - label: "I understand that a proposal that does not meet these guidelines may be closed without explanation." - required: true diff --git a/.github/ISSUE_TEMPLATE/maintenance-task-v3.yaml b/.github/ISSUE_TEMPLATE/maintenance-task-v3.yaml deleted file mode 100644 index 2a58f78922..0000000000 --- a/.github/ISSUE_TEMPLATE/maintenance-task-v3.yaml +++ /dev/null @@ -1,54 +0,0 @@ -name: "🧹 v3 Maintenance Task" -title: "🧹 [v3 Maintenance]: " -description: Describe a maintenance task for the v3 of the Fiber project. -labels: ["🧹 Updates", "v3"] - -body: - - type: markdown - id: notice - attributes: - value: | - ### Notice - - Before submitting a maintenance task, please check if a similar task has already been filed. - - Clearly outline the purpose of the maintenance task and its impact on the project. - - Use clear and understandable English. - - - type: textarea - id: task-description - attributes: - label: "Maintenance Task Description" - description: "Provide a detailed description of the maintenance task. Include any specific areas of the codebase that require attention, and the desired outcomes of this task." - placeholder: "Detail the maintenance task, specifying what needs to be done and why it is necessary." - validations: - required: true - - - type: textarea - id: impact - attributes: - label: "Impact on the Project" - description: "Explain the impact this maintenance will have on the project. Include benefits and potential risks if applicable." - placeholder: "Describe how completing this task will benefit the project, or the risks of not addressing it." - validations: - required: false - - - type: textarea - id: additional-context - attributes: - label: "Additional Context (optional)" - description: "Any additional information or context regarding the maintenance task that might be helpful." - placeholder: "Provide any additional information that may be relevant to the task at hand." - validations: - required: false - - - type: checkboxes - id: terms - attributes: - label: "Checklist:" - description: "Please confirm the following:" - options: - - label: "I have confirmed that this maintenance task is currently not being addressed." - required: true - - label: "I understand that this task will be evaluated by the maintainers and prioritized accordingly." - required: true - - label: "I am available to provide further information if needed." - required: true diff --git a/.github/PULL_REQUEST_TEMPLATE/v3-changes.md b/.github/PULL_REQUEST_TEMPLATE/v3-changes.md deleted file mode 100644 index 250037be08..0000000000 --- a/.github/PULL_REQUEST_TEMPLATE/v3-changes.md +++ /dev/null @@ -1,44 +0,0 @@ -## Description - -Please provide a clear and concise description of the changes you've made and the problem they address. Include the purpose of the change, any relevant issues it solves, and the benefits it brings to the project. If this change introduces new features or adjustments, highlight them here. - -Related to # (issue) - -## Changes Introduced - -List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide. - -- [ ] Benchmarks: Describe any performance benchmarks and improvements related to the changes. -- [ ] Documentation Update: Detail the updates made to the documentation and links to the changed files. -- [ ] Changelog/What's New: Include a summary of the additions for the upcoming release notes. -- [ ] Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes. -- [ ] API Alignment with Express: Explain how the changes align with the Express API. -- [ ] API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes. -- [ ] Examples: Provide examples demonstrating the new features or changes in action. - -## Type of Change - -Please delete options that are not relevant. - -- [ ] New feature (non-breaking change which adds functionality) -- [ ] Enhancement (improvement to existing features and functionality) -- [ ] Documentation update (changes to documentation) -- [ ] Performance improvement (non-breaking change which improves efficiency) -- [ ] Code consistency (non-breaking change which improves code reliability and robustness) - -## Checklist - -Before you submit your pull request, please make sure you meet these requirements: - -- [ ] Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage. -- [ ] Conducted a self-review of the code and provided comments for complex or critical parts. -- [ ] Updated the documentation in the `/docs/` directory for [Fiber's documentation](https://docs.gofiber.io/). -- [ ] Added or updated unit tests to validate the effectiveness of the changes or new features. -- [ ] Ensured that new and existing unit tests pass locally with the changes. -- [ ] Verified that any new dependencies are essential and have been agreed upon by the maintainers/community. -- [ ] Aimed for optimal performance with minimal allocations in the new code. -- [ ] Provided benchmarks for the new code to analyze and improve upon. - -## Commit Formatting - -Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: [CONTRIBUTING.md](https://github.com/gofiber/fiber/blob/master/.github/CONTRIBUTING.md#pull-requests-or-commits) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 323c265e79..222b26d20b 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -5,8 +5,6 @@ Explain the *details* for making this change. What existing problem does the pul Fixes # (issue) -:warning: **For changes specific to v3, please switch to the [v3 Pull Request Template](?template=v3-changes.md).** - ## Type of change Please delete options that are not relevant. diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index ebc7c6f96c..5c8b72d1d6 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -1,5 +1,7 @@ name-template: 'v$RESOLVED_VERSION' tag-template: 'v$RESOLVED_VERSION' +commitish: refs/heads/v2 +filter-by-commitish: true categories: - title: '❗ Breaking Changes' labels: diff --git a/.github/scripts/sync_docs.sh b/.github/scripts/sync_docs.sh index b9b4cefde1..8175f26d21 100755 --- a/.github/scripts/sync_docs.sh +++ b/.github/scripts/sync_docs.sh @@ -18,15 +18,16 @@ git config --global user.name "${AUTHOR_USERNAME}" git clone https://${TOKEN}@${REPO_URL} fiber-docs # Handle push event -if [ "$EVENT" == "push" ]; then - latest_commit=$(git rev-parse --short HEAD) - log_output=$(git log --oneline ${BRANCH} HEAD~1..HEAD --name-status -- docs/) - if [[ $log_output != "" ]]; then - cp -a docs/* fiber-docs/docs/${REPO_DIR} - fi - -# Handle release event -elif [ "$EVENT" == "release" ]; then +#if [ "$EVENT" == "push" ]; then +# latest_commit=$(git rev-parse --short HEAD) +# log_output=$(git log --oneline ${BRANCH} HEAD~1..HEAD --name-status -- docs/) +# if [[ $log_output != "" ]]; then +# cp -a docs/* fiber-docs/docs/${REPO_DIR} +# fi +# +## Handle release event +#el +if [ "$EVENT" == "release" ]; then major_version="${TAG_NAME%%.*}" # Form new version name diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 7625373255..42e7afd653 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -1,8 +1,7 @@ on: push: branches: - - master - - main + - v2 paths: - "**" - "!docs/**" diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 82036cc967..0476abfba2 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,8 +3,7 @@ name: "CodeQL" on: push: branches: - - master - - main + - v2 paths: - "**" - "!docs/**" diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 3defb96344..607e0fa055 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -4,8 +4,7 @@ name: golangci-lint on: push: branches: - - master - - main + - v2 pull_request: permissions: contents: read diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml index cedaab432f..3ac6e95572 100644 --- a/.github/workflows/release-drafter.yml +++ b/.github/workflows/release-drafter.yml @@ -4,8 +4,7 @@ on: push: # branches to consider in the event; optional, defaults to all branches: - - master - - main + - v2 jobs: update_release_draft: diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index eb35d75bd2..dd53569b2e 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -1,12 +1,11 @@ name: "Sync docs" on: - push: - branches: - - master - - main - paths: - - "docs/**" +# push: +# branches: +# - v2 +# paths: +# - "docs/**" release: types: [published] diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f103d914fb..a186908aa0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,8 +1,7 @@ on: push: branches: - - master - - main + - v2 paths: - "**" - "!docs/**" diff --git a/.github/workflows/vulncheck.yml b/.github/workflows/vulncheck.yml index e6d29ccb4b..f28ab5b0e2 100644 --- a/.github/workflows/vulncheck.yml +++ b/.github/workflows/vulncheck.yml @@ -3,8 +3,7 @@ name: Run govulncheck on: push: branches: - - master - - main + - v2 paths: - "**" - "!docs/**" From 7ba3137f2e6fd57c7dc198eaf5de77deb20646e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Sat, 6 Jan 2024 17:45:21 +0100 Subject: [PATCH 21/51] configure workflows for V2 branch --- .github/release-drafter.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index 5c8b72d1d6..d008535545 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -2,6 +2,10 @@ name-template: 'v$RESOLVED_VERSION' tag-template: 'v$RESOLVED_VERSION' commitish: refs/heads/v2 filter-by-commitish: true +include-labels: + - 'v2' +exclude-labels: + - 'v3' categories: - title: '❗ Breaking Changes' labels: From e524b7352468da1b788c3cdbd680ff7d1055b2f1 Mon Sep 17 00:00:00 2001 From: Jongmin Kim Date: Mon, 29 Jan 2024 02:28:47 +0900 Subject: [PATCH 22/51] Fix default value to false in docs of QueryBool (#2811) fix default value to false in docs of QueryBool --- ctx.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ctx.go b/ctx.go index 55b81cf2ee..596268e9fe 100644 --- a/ctx.go +++ b/ctx.go @@ -1222,7 +1222,7 @@ func (c *Ctx) QueryInt(key string, defaultValue ...int) int { } // QueryBool returns bool value of key string parameter in the url. -// Default to empty or invalid key is true. +// Default to empty or invalid key is false. // // Get /?name=alex&want_pizza=false&id= // QueryBool("want_pizza") == false From 8325ed086c99920f63d9b916644774e4e295eab3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Tue, 6 Feb 2024 08:40:32 +0100 Subject: [PATCH 23/51] update queryParser config --- docs/api/ctx.md | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/docs/api/ctx.md b/docs/api/ctx.md index 2c3244926f..f1121b7630 100644 --- a/docs/api/ctx.md +++ b/docs/api/ctx.md @@ -1387,9 +1387,13 @@ app.Get("/", func(c *fiber.Ctx) error { return err } - log.Println(p.Name) // john - log.Println(p.Pass) // doe - log.Println(p.Products) // [shoe, hat] + log.Println(p.Name) // john + log.Println(p.Pass) // doe + // fiber.Config{EnableSplittingOnParsers: false} - default + log.Println(p.Products) // ["shoe,hat"] + // fiber.Config{EnableSplittingOnParsers: true} + // log.Println(p.Products) // ["shoe", "hat"] + // ... }) @@ -1398,6 +1402,10 @@ app.Get("/", func(c *fiber.Ctx) error { // curl "http://localhost:3000/?name=john&pass=doe&products=shoe,hat" ``` +:::info +For more parser settings please look here [Config](fiber.md#Config) +::: + ## Range A struct containing the type and a slice of ranges will be returned. From 56d2ec7bd0d796399fcca2d4668dfc34c9ef858f Mon Sep 17 00:00:00 2001 From: RW Date: Tue, 6 Feb 2024 09:11:21 +0100 Subject: [PATCH 24/51] Update ctx.md --- docs/api/ctx.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/ctx.md b/docs/api/ctx.md index f1121b7630..52f1a3ad91 100644 --- a/docs/api/ctx.md +++ b/docs/api/ctx.md @@ -1403,7 +1403,7 @@ app.Get("/", func(c *fiber.Ctx) error { ``` :::info -For more parser settings please look here [Config](fiber.md#Config) +For more parser settings please look here [Config](fiber.md#config) ::: ## Range From 4e0f180fe3425b92d2c7b7e362182d17c21ee50b Mon Sep 17 00:00:00 2001 From: RW Date: Thu, 8 Feb 2024 08:18:26 +0100 Subject: [PATCH 25/51] Update routing.md --- docs/guide/routing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/routing.md b/docs/guide/routing.md index b6534532b0..2a1067ae6f 100644 --- a/docs/guide/routing.md +++ b/docs/guide/routing.md @@ -145,7 +145,7 @@ We have adapted the routing strongly to the express routing, but currently witho Route constraints execute when a match has occurred to the incoming URL and the URL path is tokenized into route values by parameters. The feature was intorduced in `v2.37.0` and inspired by [.NET Core](https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-6.0#route-constraints). :::caution -Constraints aren't validation for parameters. If constraint aren't valid for parameter value, Fiber returns **404 handler**. +Constraints aren't validation for parameters. If constraints aren't valid for a parameter value, Fiber returns **404 handler**. ::: | Constraint | Example | Example matches | From 58b0e113998dcea728557a1d44f430c91a4dae43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Sun, 18 Feb 2024 23:08:43 +0100 Subject: [PATCH 26/51] merge v2 in v3 --- ctx_test.go | 55 +++++++++++----------- docs/api/middleware/basicauth.md | 2 - docs/api/middleware/healthcheck.md | 18 +++---- docs/api/middleware/timeout.md | 18 +------ go.mod | 3 ++ go.sum | 6 +++ middleware/basicauth/config.go | 16 ------- middleware/csrf/config.go | 14 ------ middleware/healthcheck/config.go | 12 ++--- middleware/healthcheck/healthcheck.go | 10 ++-- middleware/healthcheck/healthcheck_test.go | 44 ++++++++--------- middleware/keyauth/config.go | 7 --- middleware/logger/tags.go | 2 +- middleware/requestid/config.go | 11 ----- middleware/timeout/timeout.go | 48 +------------------ middleware/timeout/timeout_test.go | 4 +- 16 files changed, 86 insertions(+), 184 deletions(-) diff --git a/ctx_test.go b/ctx_test.go index f57e9dba5e..206a813533 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1366,83 +1366,84 @@ func Test_Ctx_Parsers(t *testing.T) { ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" reqHeader:"class2"` } - withValues := func(t *testing.T, actionFn func(c *Ctx, testStruct *TestStruct) error) { + withValues := func(t *testing.T, actionFn func(c Ctx, testStruct *TestStruct) error) { t.Helper() - c := app.AcquireCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx() defer app.ReleaseCtx(c) testStruct := new(TestStruct) - utils.AssertEqual(t, nil, actionFn(c, testStruct)) - utils.AssertEqual(t, "foo", testStruct.Name) - utils.AssertEqual(t, 111, testStruct.Class) - utils.AssertEqual(t, "bar", testStruct.NameWithDefault) - utils.AssertEqual(t, 222, testStruct.ClassWithDefault) + require.Equal(t, nil, actionFn(c, testStruct)) + require.Equal(t, "foo", testStruct.Name) + require.Equal(t, 111, testStruct.Class) + require.Equal(t, "bar", testStruct.NameWithDefault) + require.Equal(t, 222, testStruct.ClassWithDefault) } t.Run("BodyParser:xml", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { c.Request().Header.SetContentType(MIMEApplicationXML) c.Request().SetBody([]byte(`foo111bar222`)) - return c.BodyParser(testStruct) + return c.Bind().Body(testStruct) }) }) t.Run("BodyParser:form", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { c.Request().Header.SetContentType(MIMEApplicationForm) c.Request().SetBody([]byte(`name=foo&class=111&name2=bar&class2=222`)) - return c.BodyParser(testStruct) + return c.Bind().Body(testStruct) }) }) t.Run("BodyParser:json", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { c.Request().Header.SetContentType(MIMEApplicationJSON) c.Request().SetBody([]byte(`{"name":"foo","class":111,"name2":"bar","class2":222}`)) - return c.BodyParser(testStruct) + return c.Bind().Body(testStruct) }) }) t.Run("BodyParser:multiform", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { body := []byte("--b\r\nContent-Disposition: form-data; name=\"name\"\r\n\r\nfoo\r\n--b\r\nContent-Disposition: form-data; name=\"class\"\r\n\r\n111\r\n--b\r\nContent-Disposition: form-data; name=\"name2\"\r\n\r\nbar\r\n--b\r\nContent-Disposition: form-data; name=\"class2\"\r\n\r\n222\r\n--b--") c.Request().SetBody(body) c.Request().Header.SetContentType(MIMEMultipartForm + `;boundary="b"`) c.Request().Header.SetContentLength(len(body)) - return c.BodyParser(testStruct) + return c.Bind().Body(testStruct) }) }) t.Run("CookieParser", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { c.Request().Header.Set("Cookie", "name=foo;name2=bar;class=111;class2=222") - return c.CookieParser(testStruct) + return c.Bind().Cookie(testStruct) }) }) t.Run("QueryParser", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { c.Request().URI().SetQueryString("name=foo&name2=bar&class=111&class2=222") - return c.QueryParser(testStruct) + return c.Bind().Query(testStruct) }) }) t.Run("ParamsParser", func(t *testing.T) { - t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { - c.route = &Route{Params: []string{"name", "name2", "class", "class2"}} - c.values = [30]string{"foo", "bar", "111", "222"} - return c.ParamsParser(testStruct) - }) + t.Skip("ParamsParser is not ready for v3") + //t.Parallel() + //withValues(t, func(c Ctx, testStruct *TestStruct) error { + // c.route = &Route{Params: []string{"name", "name2", "class", "class2"}} + // c.values = [30]string{"foo", "bar", "111", "222"} + // return c.ParamsParser(testStruct) + //}) }) t.Run("ReqHeaderParser", func(t *testing.T) { t.Parallel() - withValues(t, func(c *Ctx, testStruct *TestStruct) error { + withValues(t, func(c Ctx, testStruct *TestStruct) error { c.Request().Header.Add("name", "foo") c.Request().Header.Add("name2", "bar") c.Request().Header.Add("class", "111") c.Request().Header.Add("class2", "222") - return c.ReqHeaderParser(testStruct) + return c.Bind().Header(testStruct) }) }) } diff --git a/docs/api/middleware/basicauth.md b/docs/api/middleware/basicauth.md index 4f6e327e43..246945ce7b 100644 --- a/docs/api/middleware/basicauth.md +++ b/docs/api/middleware/basicauth.md @@ -78,8 +78,6 @@ func handler(c fiber.Ctx) error { | Realm | `string` | Realm is a string to define the realm attribute of BasicAuth. The realm identifies the system to authenticate against and can be used by clients to save credentials. | `"Restricted"` | | Authorizer | `func(string, string) bool` | Authorizer defines a function to check the credentials. It will be called with a username and password and is expected to return true or false to indicate approval. | `nil` | | Unauthorized | `fiber.Handler` | Unauthorized defines the response body for unauthorized responses. | `nil` | -| ContextUsername | `interface{}` | ContextUsername is the key to store the username in Locals. | `"username"` | -| ContextPassword | `interface{}` | ContextPassword is the key to store the password in Locals. | `"password"` | ## Default Config diff --git a/docs/api/middleware/healthcheck.md b/docs/api/middleware/healthcheck.md index 641c236b1b..666d51ef12 100644 --- a/docs/api/middleware/healthcheck.md +++ b/docs/api/middleware/healthcheck.md @@ -31,8 +31,8 @@ func New(config Config) fiber.Handler Import the middleware package that is part of the [Fiber](https://github.com/gofiber/fiber) web framework ```go import ( - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/healthcheck" + "github.com/gofiber/fiber/v3" + "github.com/gofiber/fiber/v3/middleware/healthcheck" ) ``` @@ -44,11 +44,11 @@ app.Use(healthcheck.New()) // Or extend your config for customization app.Use(healthcheck.New(healthcheck.Config{ - LivenessProbe: func(c *fiber.Ctx) bool { + LivenessProbe: func(c fiber.Ctx) bool { return true }, LivenessEndpoint: "/live", - ReadinessProbe: func(c *fiber.Ctx) bool { + ReadinessProbe: func(c fiber.Ctx) bool { return serviceA.Ready() && serviceB.Ready() && ... }, ReadinessEndpoint: "/ready", @@ -62,13 +62,13 @@ type Config struct { // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil - Next func(c *fiber.Ctx) bool + Next func(fiber.Ctx) bool // Function used for checking the liveness of the application. Returns true if the application // is running and false if it is not. The liveness probe is typically used to indicate if // the application is in a state where it can handle requests (e.g., the server is up and running). // - // Optional. Default: func(c *fiber.Ctx) bool { return true } + // Optional. Default: func(c fiber.Ctx) bool { return true } LivenessProbe HealthChecker // HTTP endpoint at which the liveness probe will be available. @@ -80,7 +80,7 @@ type Config struct { // is ready to process requests and false otherwise. The readiness probe typically checks if all necessary // services, databases, and other dependencies are available for the application to function correctly. // - // Optional. Default: func(c *fiber.Ctx) bool { return true } + // Optional. Default: func(c fiber.Ctx) bool { return true } ReadinessProbe HealthChecker // HTTP endpoint at which the readiness probe will be available. @@ -93,9 +93,9 @@ type Config struct { The default configuration used by this middleware is defined as follows: ```go -func defaultLivenessProbe(*fiber.Ctx) bool { return true } +func defaultLivenessProbe(fiber.Ctx) bool { return true } -func defaultReadinessProbe(*fiber.Ctx) bool { return true } +func defaultReadinessProbe(fiber.Ctx) bool { return true } var ConfigDefault = Config{ LivenessProbe: defaultLivenessProbe, diff --git a/docs/api/middleware/timeout.md b/docs/api/middleware/timeout.md index 059272fc21..e5f77546a0 100644 --- a/docs/api/middleware/timeout.md +++ b/docs/api/middleware/timeout.md @@ -8,14 +8,6 @@ There exist two distinct implementations of timeout middleware [Fiber](https://g **New** -Wraps a `fiber.Handler` with a timeout. If the handler takes longer than the given duration to return, the timeout error is set and forwarded to the centralized [ErrorHandler](https://docs.gofiber.io/error-handling). - -:::caution -This has been deprecated since it raises race conditions. -::: - -**NewWithContext** - As a `fiber.Handler` wrapper, it creates a context with `context.WithTimeout` and pass it in `UserContext`. If the context passed executions (eg. DB ops, Http calls) takes longer than the given duration to return, the timeout error is set and forwarded to the centralized `ErrorHandler`. @@ -27,7 +19,6 @@ It does not cancel long running executions. Underlying executions must handle ti ```go func New(handler fiber.Handler, timeout time.Duration, timeoutErrors ...error) fiber.Handler -func NewWithContext(handler fiber.Handler, timeout time.Duration, timeoutErrors ...error) fiber.Handler ``` ## Examples @@ -46,12 +37,7 @@ After you initiate your Fiber app, you can use the following possibilities: ```go func main() { app := fiber.New() -<<<<<<< HEAD:middleware/timeout/README.md - h := func(c fiber.Ctx) error { -======= - h := func(c fiber.Ctx) error { ->>>>>>> origin/master:docs/api/middleware/timeout.md sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms") if err := sleepWithContext(c.UserContext(), sleepTime); err != nil { return fmt.Errorf("%w: execution error", err) @@ -105,7 +91,7 @@ func main() { return nil } - app.Get("/foo/:sleepTime", timeout.NewWithContext(h, 2*time.Second, ErrFooTimeOut)) + app.Get("/foo/:sleepTime", timeout.New(h, 2*time.Second, ErrFooTimeOut)) log.Fatal(app.Listen(":3000")) } @@ -144,7 +130,7 @@ func main() { return nil } - app.Get("/foo", timeout.NewWithContext(handler, 10*time.Second)) + app.Get("/foo", timeout.New(handler, 10*time.Second)) log.Fatal(app.Listen(":3000")) } ``` diff --git a/go.mod b/go.mod index 18a074025e..8411e1d122 100644 --- a/go.mod +++ b/go.mod @@ -3,6 +3,7 @@ module github.com/gofiber/fiber/v3 go 1.20 require ( + github.com/gofiber/fiber/v2 v2.52.0 github.com/gofiber/utils/v2 v2.0.0-beta.3 github.com/google/uuid v1.6.0 github.com/mattn/go-colorable v0.1.13 @@ -17,8 +18,10 @@ require ( github.com/andybalholm/brotli v1.1.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/klauspost/compress v1.17.6 // indirect + github.com/mattn/go-runewidth v0.0.15 // indirect github.com/philhofer/fwd v1.1.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/rivo/uniseg v0.2.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect golang.org/x/sys v0.17.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index e74a99a27b..82eafabc24 100644 --- a/go.sum +++ b/go.sum @@ -2,6 +2,8 @@ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1 github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gofiber/fiber/v2 v2.52.0 h1:S+qXi7y+/Pgvqq4DrSmREGiFwtB7Bu6+QFLuIHYw/UE= +github.com/gofiber/fiber/v2 v2.52.0/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= github.com/gofiber/utils/v2 v2.0.0-beta.3 h1:pfOhUDDVjBJpkWv6C5jaDyYLvpui7zQ97zpyFFsUOKw= github.com/gofiber/utils/v2 v2.0.0-beta.3/go.mod h1:jsl17+MsKfwJjM3ONCE9Rzji/j8XNbwjhUVTjzgfDCo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= @@ -13,10 +15,14 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= +github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0= diff --git a/middleware/basicauth/config.go b/middleware/basicauth/config.go index e2d2e38a12..1aa050a0e2 100644 --- a/middleware/basicauth/config.go +++ b/middleware/basicauth/config.go @@ -40,16 +40,6 @@ type Config struct { // // Optional. Default: nil Unauthorized fiber.Handler - - // ContextUser is the key to store the username in Locals - // - // Optional. Default: "username" - ContextUsername interface{} - - // ContextPass is the key to store the password in Locals - // - // Optional. Default: "password" - ContextPassword interface{} } // ConfigDefault is the default config @@ -93,11 +83,5 @@ func configDefault(config ...Config) Config { return c.SendStatus(fiber.StatusUnauthorized) } } - if cfg.ContextUsername == nil { - cfg.ContextUsername = ConfigDefault.ContextUsername - } - if cfg.ContextPassword == nil { - cfg.ContextPassword = ConfigDefault.ContextPassword - } return cfg } diff --git a/middleware/csrf/config.go b/middleware/csrf/config.go index 9193f47fde..3902555dbc 100644 --- a/middleware/csrf/config.go +++ b/middleware/csrf/config.go @@ -89,12 +89,6 @@ type Config struct { // Default: "csrfToken" SessionKey string - // Context key to store generated CSRF token into context. - // If left empty, token will not be stored in context. - // - // Optional. Default: "" - ContextKey interface{} - // KeyGenerator creates a new CSRF token // // Optional. Default: utils.UUID @@ -111,11 +105,6 @@ type Config struct { // // Optional. Default will create an Extractor based on KeyLookup. Extractor func(c fiber.Ctx) (string, error) - - // HandlerContextKey is used to store the CSRF Handler into context - // - // Default: "fiber.csrf.handler" - HandlerContextKey interface{} } const HeaderName = "X-Csrf-Token" @@ -169,9 +158,6 @@ func configDefault(config ...Config) Config { if cfg.SessionKey == "" { cfg.SessionKey = ConfigDefault.SessionKey } - if cfg.HandlerContextKey == nil { - cfg.HandlerContextKey = ConfigDefault.HandlerContextKey - } // Generate the correct extractor to get the token from the correct location selectors := strings.Split(cfg.KeyLookup, ":") diff --git a/middleware/healthcheck/config.go b/middleware/healthcheck/config.go index d4e5fac1b0..59916fc869 100644 --- a/middleware/healthcheck/config.go +++ b/middleware/healthcheck/config.go @@ -1,7 +1,7 @@ package healthcheck import ( - "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v3" ) // Config defines the configuration options for the healthcheck middleware. @@ -9,13 +9,13 @@ type Config struct { // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil - Next func(c *fiber.Ctx) bool + Next func(fiber.Ctx) bool // Function used for checking the liveness of the application. Returns true if the application // is running and false if it is not. The liveness probe is typically used to indicate if // the application is in a state where it can handle requests (e.g., the server is up and running). // - // Optional. Default: func(c *fiber.Ctx) bool { return true } + // Optional. Default: func(c fiber.Ctx) bool { return true } LivenessProbe HealthChecker // HTTP endpoint at which the liveness probe will be available. @@ -27,7 +27,7 @@ type Config struct { // is ready to process requests and false otherwise. The readiness probe typically checks if all necessary // services, databases, and other dependencies are available for the application to function correctly. // - // Optional. Default: func(c *fiber.Ctx) bool { return true } + // Optional. Default: func(c fiber.Ctx) bool { return true } ReadinessProbe HealthChecker // HTTP endpoint at which the readiness probe will be available. @@ -40,9 +40,9 @@ const ( DefaultReadinessEndpoint = "/readyz" ) -func defaultLivenessProbe(*fiber.Ctx) bool { return true } +func defaultLivenessProbe(fiber.Ctx) bool { return true } -func defaultReadinessProbe(*fiber.Ctx) bool { return true } +func defaultReadinessProbe(fiber.Ctx) bool { return true } // ConfigDefault is the default config var ConfigDefault = Config{ diff --git a/middleware/healthcheck/healthcheck.go b/middleware/healthcheck/healthcheck.go index 14ff33430c..b34c11d211 100644 --- a/middleware/healthcheck/healthcheck.go +++ b/middleware/healthcheck/healthcheck.go @@ -1,17 +1,17 @@ package healthcheck import ( - "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v3" ) // HealthChecker defines a function to check liveness or readiness of the application -type HealthChecker func(*fiber.Ctx) bool +type HealthChecker func(fiber.Ctx) bool -// ProbeCheckerHandler defines a function that returns a ProbeChecker +// HealthCheckerHandler defines a function that returns a HealthChecker type HealthCheckerHandler func(HealthChecker) fiber.Handler func healthCheckerHandler(checker HealthChecker) fiber.Handler { - return func(c *fiber.Ctx) error { + return func(c fiber.Ctx) error { if checker == nil { return c.Next() } @@ -30,7 +30,7 @@ func New(config ...Config) fiber.Handler { isLiveHandler := healthCheckerHandler(cfg.LivenessProbe) isReadyHandler := healthCheckerHandler(cfg.ReadinessProbe) - return func(c *fiber.Ctx) error { + return func(c fiber.Ctx) error { // Don't execute middleware if Next returns true if cfg.Next != nil && cfg.Next(c) { return c.Next() diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index df0165f158..af04f91972 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -1,12 +1,12 @@ package healthcheck import ( + "github.com/stretchr/testify/require" "net/http/httptest" "testing" "time" - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/utils" + "github.com/gofiber/fiber/v3" "github.com/valyala/fasthttp" ) @@ -17,12 +17,12 @@ func Test_HealthCheck_Default(t *testing.T) { app.Use(New()) req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/readyz", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusOK, req.StatusCode) req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusOK, req.StatusCode) } func Test_HealthCheck_Custom(t *testing.T) { @@ -37,11 +37,11 @@ func Test_HealthCheck_Custom(t *testing.T) { }() app.Use(New(Config{ - LivenessProbe: func(c *fiber.Ctx) bool { + LivenessProbe: func(c fiber.Ctx) bool { return true }, LivenessEndpoint: "/live", - ReadinessProbe: func(c *fiber.Ctx) bool { + ReadinessProbe: func(c fiber.Ctx) bool { select { case <-c1: return true @@ -54,30 +54,30 @@ func Test_HealthCheck_Custom(t *testing.T) { // Live should return 200 with GET request req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/live", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusOK, req.StatusCode) // Live should return 404 with POST request req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 404 with POST request req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 503 with GET request before the channel is closed req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusServiceUnavailable, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusServiceUnavailable, req.StatusCode) time.Sleep(1 * time.Second) // Ready should return 200 with GET request after the channel is closed req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusOK, req.StatusCode) } func Test_HealthCheck_Next(t *testing.T) { @@ -86,14 +86,14 @@ func Test_HealthCheck_Next(t *testing.T) { app := fiber.New() app.Use(New(Config{ - Next: func(c *fiber.Ctx) bool { + Next: func(c fiber.Ctx) bool { return true }, })) req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) + require.Equal(t, nil, err) + require.Equal(t, fiber.StatusNotFound, req.StatusCode) } func Benchmark_HealthCheck(b *testing.B) { @@ -113,5 +113,5 @@ func Benchmark_HealthCheck(b *testing.B) { h(fctx) } - utils.AssertEqual(b, fiber.StatusOK, fctx.Response.Header.StatusCode()) + require.Equal(b, fiber.StatusOK, fctx.Response.Header.StatusCode()) } diff --git a/middleware/keyauth/config.go b/middleware/keyauth/config.go index 926e7308f8..3b02a9e1fa 100644 --- a/middleware/keyauth/config.go +++ b/middleware/keyauth/config.go @@ -38,10 +38,6 @@ type Config struct { // Validator is a function to validate key. Validator func(fiber.Ctx, string) (bool, error) - - // Context key to store the bearertoken from the token into context. - // Optional. Default: "token". - ContextKey interface{} } // ConfigDefault is the default config @@ -86,9 +82,6 @@ func configDefault(config ...Config) Config { if cfg.Validator == nil { panic("fiber: keyauth middleware requires a validator function") } - if cfg.ContextKey == nil { - cfg.ContextKey = ConfigDefault.ContextKey - } return cfg } diff --git a/middleware/logger/tags.go b/middleware/logger/tags.go index 12dcd87fcd..8d147fd05d 100644 --- a/middleware/logger/tags.go +++ b/middleware/logger/tags.go @@ -144,7 +144,7 @@ func createTagMap(cfg *Config) map[string]LogFunc { TagReset: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Reset) }, - TagError: func(output Buffer, _ fiber.Ctx, data *Data, _ string) (int, error) { + TagError: func(output Buffer, c fiber.Ctx, data *Data, _ string) (int, error) { if data.ChainErr != nil { if cfg.enableColors { colors := c.App().Config().ColorScheme diff --git a/middleware/requestid/config.go b/middleware/requestid/config.go index cdbb82fb24..16eddbdcf8 100644 --- a/middleware/requestid/config.go +++ b/middleware/requestid/config.go @@ -21,14 +21,6 @@ type Config struct { // // Optional. Default: utils.UUID Generator func() string - - // ContextKey defines the key used when storing the request ID in - // the locals for a specific request. - // Should be a private type instead of string, but too many apps probably - // rely on this exact value. - // - // Optional. Default: "requestid" - ContextKey interface{} } // ConfigDefault is the default config @@ -58,8 +50,5 @@ func configDefault(config ...Config) Config { if cfg.Generator == nil { cfg.Generator = ConfigDefault.Generator } - if cfg.ContextKey == nil { - cfg.ContextKey = ConfigDefault.ContextKey - } return cfg } diff --git a/middleware/timeout/timeout.go b/middleware/timeout/timeout.go index 7baa0e7056..5a9711ce22 100644 --- a/middleware/timeout/timeout.go +++ b/middleware/timeout/timeout.go @@ -3,57 +3,13 @@ package timeout import ( "context" "errors" - "sync" "time" - "github.com/gofiber/fiber/v3/log" - "github.com/gofiber/fiber/v3" ) -var once sync.Once - -// New wraps a handler and aborts the process of the handler if the timeout is reached. -// -// Deprecated: This implementation contains data race issues. Use NewWithContext instead. -// Find documentation and sample usage on https://docs.gofiber.io/api/middleware/timeout -func New(handler fiber.Handler, timeout time.Duration) fiber.Handler { - once.Do(func() { - log.Warn("[TIMEOUT] timeout contains data race issues, not ready for production!") - }) - - if timeout <= 0 { - return handler - } - - // logic is from fasthttp.TimeoutWithCodeHandler https://github.com/valyala/fasthttp/blob/master/server.go#L418 - return func(c fiber.Ctx) error { - ch := make(chan struct{}, 1) - - go func() { - defer func() { - if err := recover(); err != nil { - log.Errorf("[TIMEOUT] recover error %v", err) - } - }() - if err := handler(c); err != nil { - log.Errorf("[TIMEOUT] handler error %v", err) - } - ch <- struct{}{} - }() - - select { - case <-ch: - case <-time.After(timeout): - return fiber.ErrRequestTimeout - } - - return nil - } -} - -// NewWithContext implementation of timeout middleware. Set custom errors(context.DeadlineExceeded vs) for get fiber.ErrRequestTimeout response. -func NewWithContext(h fiber.Handler, t time.Duration, tErrs ...error) fiber.Handler { +// New implementation of timeout middleware. Set custom errors(context.DeadlineExceeded vs) for get fiber.ErrRequestTimeout response. +func New(h fiber.Handler, t time.Duration, tErrs ...error) fiber.Handler { return func(ctx fiber.Ctx) error { timeoutContext, cancel := context.WithTimeout(ctx.UserContext(), t) defer cancel() diff --git a/middleware/timeout/timeout_test.go b/middleware/timeout/timeout_test.go index 87292c66f6..b08445eb2a 100644 --- a/middleware/timeout/timeout_test.go +++ b/middleware/timeout/timeout_test.go @@ -17,7 +17,7 @@ func Test_WithContextTimeout(t *testing.T) { t.Parallel() // fiber instance app := fiber.New() - h := NewWithContext(func(c fiber.Ctx) error { + h := New(func(c fiber.Ctx) error { sleepTime, err := time.ParseDuration(c.Params("sleepTime") + "ms") require.NoError(t, err) if err := sleepWithContext(c.UserContext(), sleepTime, context.DeadlineExceeded); err != nil { @@ -49,7 +49,7 @@ func Test_WithContextTimeoutWithCustomError(t *testing.T) { t.Parallel() // fiber instance app := fiber.New() - h := NewWithContext(func(c fiber.Ctx) error { + h := New(func(c fiber.Ctx) error { sleepTime, err := time.ParseDuration(c.Params("sleepTime") + "ms") require.NoError(t, err) if err := sleepWithContext(c.UserContext(), sleepTime, ErrFooTimeOut); err != nil { From b75e7f8b9343067b36bbe08b2077c6e6b664575d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Sun, 18 Feb 2024 23:13:10 +0100 Subject: [PATCH 27/51] merge v2 in v3 --- docs/api/middleware/logger.md | 30 +++++++++++++++--------------- middleware/logger/config.go | 4 ++-- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index 014a5e182e..41f399ad2d 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -96,27 +96,27 @@ Writing to os.File is goroutine-safe, but if you are using a custom Output that ### Config -| Property | Type | Description | Default | -|:-----------------|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------|:-------------------------| -| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | -| Done | `func(fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` | -| CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` | -| Format | `string` | Format defines the logging tags. | `[${time}] ${status} - ${latency} ${method} ${path}\n` | -| TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` | -| TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` | -| TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` | -| Output | `io.Writer` | Output is a writer where logs are written. | `os.Stdout` | -| DisableColors | `bool` | DisableColors defines if the logs output should be colorized. | `false` | -| enableColors | `bool` | Internal field for enabling colors in the log output. (This is not a user-configurable field) | - | -| enableLatency | `bool` | Internal field for enabling latency measurement in logs. (This is not a user-configurable field) | - | -| timeZoneLocation | `*time.Location` | Internal field for the time zone location. (This is not a user-configurable field) | - | +| Property | Type | Description | Default | +|:-----------------|:---------------------------|:---------------------------------------------------------------------------------------------------------------------------------|:----------------------------------------------------------------------| +| Next | `func(fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | +| Done | `func(fiber.Ctx, []byte)` | Done is a function that is called after the log string for a request is written to Output, and pass the log string as parameter. | `nil` | +| CustomTags | `map[string]LogFunc` | tagFunctions defines the custom tag action. | `map[string]LogFunc` | +| Format | `string` | Format defines the logging tags. | `[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n` | +| TimeFormat | `string` | TimeFormat defines the time format for log timestamps. | `15:04:05` | +| TimeZone | `string` | TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc | `"Local"` | +| TimeInterval | `time.Duration` | TimeInterval is the delay before the timestamp is updated. | `500 * time.Millisecond` | +| Output | `io.Writer` | Output is a writer where logs are written. | `os.Stdout` | +| DisableColors | `bool` | DisableColors defines if the logs output should be colorized. | `false` | +| enableColors | `bool` | Internal field for enabling colors in the log output. (This is not a user-configurable field) | - | +| enableLatency | `bool` | Internal field for enabling latency measurement in logs. (This is not a user-configurable field) | - | +| timeZoneLocation | `*time.Location` | Internal field for the time zone location. (This is not a user-configurable field) | - | ## Default Config ```go var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "[${time}] ${status} - ${latency} ${method} ${path}\n", + Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/logger/config.go b/middleware/logger/config.go index 3d2417bc8b..dcf4d45241 100644 --- a/middleware/logger/config.go +++ b/middleware/logger/config.go @@ -28,7 +28,7 @@ type Config struct { // Format defines the logging tags // - // Optional. Default: ${time} | ${status} | ${latency} | ${ip} | ${method} | ${path} | ${error}\n + // Optional. Default: [${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error} Format string // TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html @@ -109,7 +109,7 @@ var ConfigDefault = Config{ } // default logging format for Fiber's default logger -var defaultFormat = "[${time}] ${status} - ${latency} ${method} ${path}\n" +var defaultFormat = "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n" // Helper function to set default values func configDefault(config ...Config) Config { From 980b52b3801b52b11db372ae2b9c667b39ed1560 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Sun, 18 Feb 2024 23:21:29 +0100 Subject: [PATCH 28/51] lint fixes --- ctx_test.go | 14 ++++++------ docs/api/app.md | 4 ++-- middleware/cors/cors_test.go | 14 ++++++------ middleware/csrf/csrf_test.go | 2 +- middleware/healthcheck/healthcheck_test.go | 25 +++++++++++----------- middleware/redirect/redirect.go | 2 +- 6 files changed, 31 insertions(+), 30 deletions(-) diff --git a/ctx_test.go b/ctx_test.go index 206a813533..97b47f14d2 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1372,7 +1372,7 @@ func Test_Ctx_Parsers(t *testing.T) { defer app.ReleaseCtx(c) testStruct := new(TestStruct) - require.Equal(t, nil, actionFn(c, testStruct)) + require.NoError(t, actionFn(c, testStruct)) require.Equal(t, "foo", testStruct.Name) require.Equal(t, 111, testStruct.Class) require.Equal(t, "bar", testStruct.NameWithDefault) @@ -1429,12 +1429,12 @@ func Test_Ctx_Parsers(t *testing.T) { }) t.Run("ParamsParser", func(t *testing.T) { t.Skip("ParamsParser is not ready for v3") - //t.Parallel() - //withValues(t, func(c Ctx, testStruct *TestStruct) error { - // c.route = &Route{Params: []string{"name", "name2", "class", "class2"}} - // c.values = [30]string{"foo", "bar", "111", "222"} - // return c.ParamsParser(testStruct) - //}) + // t.Parallel() + // withValues(t, func(c Ctx, testStruct *TestStruct) error { + // c.route = &Route{Params: []string{"name", "name2", "class", "class2"}} + // c.values = [30]string{"foo", "bar", "111", "222"} + // return c.ParamsParser(testStruct) + // }) }) t.Run("ReqHeaderParser", func(t *testing.T) { t.Parallel() diff --git a/docs/api/app.md b/docs/api/app.md index 250321fde8..d44944f7dd 100644 --- a/docs/api/app.md +++ b/docs/api/app.md @@ -93,7 +93,7 @@ type Static struct { // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil - Next func(c *Ctx) bool + Next func(c Ctx) bool } ``` @@ -664,4 +664,4 @@ Hooks is a method to return [hooks](../guide/hooks.md) property. ```go title="Signature" func (app *App) Hooks() *Hooks -``` \ No newline at end of file +``` diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 640a58cec6..a887bee7b2 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -377,7 +377,7 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { Name: "AllowOriginsDefined/AllowOriginsFuncReturnsTrue/OriginAllowed", Config: Config{ AllowOrigins: "http://aaa.com", - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return true }, }, @@ -388,7 +388,7 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { Name: "AllowOriginsDefined/AllowOriginsFuncReturnsTrue/OriginNotAllowed", Config: Config{ AllowOrigins: "http://aaa.com", - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return true }, }, @@ -399,7 +399,7 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { Name: "AllowOriginsDefined/AllowOriginsFuncReturnsFalse/OriginAllowed", Config: Config{ AllowOrigins: "http://aaa.com", - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return false }, }, @@ -410,7 +410,7 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { Name: "AllowOriginsDefined/AllowOriginsFuncReturnsFalse/OriginNotAllowed", Config: Config{ AllowOrigins: "http://aaa.com", - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return false }, }, @@ -430,7 +430,7 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { Name: "AllowOriginsEmpty/AllowOriginsFuncReturnsTrue/OriginAllowed", Config: Config{ AllowOrigins: "", - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return true }, }, @@ -441,7 +441,7 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { Name: "AllowOriginsEmpty/AllowOriginsFuncReturnsFalse/OriginNotAllowed", Config: Config{ AllowOrigins: "", - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return false }, }, @@ -481,7 +481,7 @@ func Test_CORS_AllowCredetials(t *testing.T) { Name: "AllowOriginsFuncDefined", Config: Config{ AllowCredentials: true, - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return true }, }, diff --git a/middleware/csrf/csrf_test.go b/middleware/csrf/csrf_test.go index fe39271977..83504bb2f8 100644 --- a/middleware/csrf/csrf_test.go +++ b/middleware/csrf/csrf_test.go @@ -949,7 +949,7 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // }) // resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) -// require.Equal(t, nil, err) +// require.NoError(t, err) // require.Equal(t, fiber.StatusOK, resp.StatusCode) // var token string diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index af04f91972..3d1173a302 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -1,12 +1,12 @@ package healthcheck import ( - "github.com/stretchr/testify/require" "net/http/httptest" "testing" "time" "github.com/gofiber/fiber/v3" + "github.com/stretchr/testify/require" "github.com/valyala/fasthttp" ) @@ -17,11 +17,12 @@ func Test_HealthCheck_Default(t *testing.T) { app.Use(New()) req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/readyz", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) + require.NoError(t, err) require.Equal(t, fiber.StatusOK, req.StatusCode) req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusOK, req.StatusCode) } @@ -37,11 +38,11 @@ func Test_HealthCheck_Custom(t *testing.T) { }() app.Use(New(Config{ - LivenessProbe: func(c fiber.Ctx) bool { + LivenessProbe: func(_ fiber.Ctx) bool { return true }, LivenessEndpoint: "/live", - ReadinessProbe: func(c fiber.Ctx) bool { + ReadinessProbe: func(_ fiber.Ctx) bool { select { case <-c1: return true @@ -54,29 +55,29 @@ func Test_HealthCheck_Custom(t *testing.T) { // Live should return 200 with GET request req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/live", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusOK, req.StatusCode) // Live should return 404 with POST request req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 404 with POST request req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 503 with GET request before the channel is closed req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusServiceUnavailable, req.StatusCode) time.Sleep(1 * time.Second) // Ready should return 200 with GET request after the channel is closed req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusOK, req.StatusCode) } @@ -86,13 +87,13 @@ func Test_HealthCheck_Next(t *testing.T) { app := fiber.New() app.Use(New(Config{ - Next: func(c fiber.Ctx) bool { + Next: func(_ fiber.Ctx) bool { return true }, })) req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) } diff --git a/middleware/redirect/redirect.go b/middleware/redirect/redirect.go index 06e972be8c..4fb7bb8830 100644 --- a/middleware/redirect/redirect.go +++ b/middleware/redirect/redirect.go @@ -34,7 +34,7 @@ func New(config ...Config) fiber.Handler { if queryString != "" { queryString = "?" + queryString } - return c.Redirect().Status(cfg.StatusCode).To(replacer.Replace(v)+queryString) + return c.Redirect().Status(cfg.StatusCode).To(replacer.Replace(v) + queryString) } } return c.Next() From a84a7cee7edcfb12c6448a0b408d3f804c38743f Mon Sep 17 00:00:00 2001 From: Giovanni Rivera Date: Sun, 18 Feb 2024 18:21:23 -0800 Subject: [PATCH 29/51] :books: Doc: Fix code snippet indentation in /docs/api/middleware/keyauth.md Removes an an extra level of indentation in line 51 of `keyauth.md` [here](https://github.com/gofiber/fiber/blob/v2/docs/api/middleware/keyauth.md?plain=1#L51) --- docs/api/middleware/keyauth.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/middleware/keyauth.md b/docs/api/middleware/keyauth.md index 1a719c134d..4705c2e667 100644 --- a/docs/api/middleware/keyauth.md +++ b/docs/api/middleware/keyauth.md @@ -47,7 +47,7 @@ func main() { Validator: validateAPIKey, })) - app.Get("/", func(c *fiber.Ctx) error { + app.Get("/", func(c *fiber.Ctx) error { return c.SendString("Successfully authenticated!") }) From 5e30112d08b1a76f38f838a175988a3712846bd7 Mon Sep 17 00:00:00 2001 From: Lucas Lemos Date: Mon, 19 Feb 2024 10:28:58 -0300 Subject: [PATCH 30/51] fix: healthcheck middleware not working with route group (#2863) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix: healthcheck middleware not working with route group * perf: change verification method to improve perf * Update healthcheck_test.go * test: add not matching route test for strict routing * add more test cases * correct tests * correct test helpers * correct tests * correct tests --------- Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Co-authored-by: René Werner --- middleware/healthcheck/healthcheck.go | 19 ++- middleware/healthcheck/healthcheck_test.go | 178 +++++++++++++++++---- 2 files changed, 163 insertions(+), 34 deletions(-) diff --git a/middleware/healthcheck/healthcheck.go b/middleware/healthcheck/healthcheck.go index 14ff33430c..c9d6a6476b 100644 --- a/middleware/healthcheck/healthcheck.go +++ b/middleware/healthcheck/healthcheck.go @@ -2,6 +2,7 @@ package healthcheck import ( "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/utils" ) // HealthChecker defines a function to check liveness or readiness of the application @@ -40,11 +41,19 @@ func New(config ...Config) fiber.Handler { return c.Next() } - switch c.Path() { - case cfg.ReadinessEndpoint: - return isReadyHandler(c) - case cfg.LivenessEndpoint: - return isLiveHandler(c) + prefixCount := len(utils.TrimRight(c.Route().Path, '/')) + if len(c.Path()) >= prefixCount { + checkPath := c.Path()[prefixCount:] + checkPathTrimmed := checkPath + if !c.App().Config().StrictRouting { + checkPathTrimmed = utils.TrimRight(checkPath, '/') + } + switch { + case checkPath == cfg.ReadinessEndpoint || checkPathTrimmed == cfg.ReadinessEndpoint: + return isReadyHandler(c) + case checkPath == cfg.LivenessEndpoint || checkPathTrimmed == cfg.LivenessEndpoint: + return isLiveHandler(c) + } } return c.Next() diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index df0165f158..84fbb43da0 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -1,28 +1,120 @@ package healthcheck import ( + "fmt" "net/http/httptest" "testing" - "time" "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/utils" "github.com/valyala/fasthttp" ) +func shouldGiveStatus(t *testing.T, app *fiber.App, path string, expectedStatus int) { + t.Helper() + req, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, nil)) + utils.AssertEqual(t, nil, err) + utils.AssertEqual(t, expectedStatus, req.StatusCode, "path: "+path+" should match "+fmt.Sprint(expectedStatus)) +} + +func shouldGiveOK(t *testing.T, app *fiber.App, path string) { + t.Helper() + shouldGiveStatus(t, app, path, fiber.StatusOK) +} + +func shouldGiveNotFound(t *testing.T, app *fiber.App, path string) { + t.Helper() + shouldGiveStatus(t, app, path, fiber.StatusNotFound) +} + +func Test_HealthCheck_Strict_Routing_Default(t *testing.T) { + t.Parallel() + + app := fiber.New(fiber.Config{ + StrictRouting: true, + }) + + app.Use(New()) + + shouldGiveOK(t, app, "/readyz") + shouldGiveOK(t, app, "/livez") + shouldGiveNotFound(t, app, "/readyz/") + shouldGiveNotFound(t, app, "/livez/") + shouldGiveNotFound(t, app, "/notDefined/readyz") + shouldGiveNotFound(t, app, "/notDefined/livez") +} + +func Test_HealthCheck_Group_Default(t *testing.T) { + t.Parallel() + + app := fiber.New() + app.Group("/v1", New()) + v2Group := app.Group("/v2/") + customer := v2Group.Group("/customer/") + customer.Use(New()) + + v3Group := app.Group("/v3/") + v3Group.Group("/todos/", New(Config{ReadinessEndpoint: "/readyz/", LivenessEndpoint: "/livez/"})) + + shouldGiveOK(t, app, "/v1/readyz") + shouldGiveOK(t, app, "/v1/livez") + shouldGiveOK(t, app, "/v1/readyz/") + shouldGiveOK(t, app, "/v1/livez/") + shouldGiveOK(t, app, "/v2/customer/readyz") + shouldGiveOK(t, app, "/v2/customer/livez") + shouldGiveOK(t, app, "/v2/customer/readyz/") + shouldGiveOK(t, app, "/v2/customer/livez/") + shouldGiveNotFound(t, app, "/v3/todos/readyz") + shouldGiveNotFound(t, app, "/v3/todos/livez") + shouldGiveOK(t, app, "/v3/todos/readyz/") + shouldGiveOK(t, app, "/v3/todos/livez/") + shouldGiveNotFound(t, app, "/notDefined/readyz") + shouldGiveNotFound(t, app, "/notDefined/livez") + shouldGiveNotFound(t, app, "/notDefined/readyz/") + shouldGiveNotFound(t, app, "/notDefined/livez/") + + // strict routing + app = fiber.New(fiber.Config{ + StrictRouting: true, + }) + app.Group("/v1", New()) + v2Group = app.Group("/v2/") + customer = v2Group.Group("/customer/") + customer.Use(New()) + + v3Group = app.Group("/v3/") + v3Group.Group("/todos/", New(Config{ReadinessEndpoint: "/readyz/", LivenessEndpoint: "/livez/"})) + + shouldGiveOK(t, app, "/v1/readyz") + shouldGiveOK(t, app, "/v1/livez") + shouldGiveNotFound(t, app, "/v1/readyz/") + shouldGiveNotFound(t, app, "/v1/livez/") + shouldGiveOK(t, app, "/v2/customer/readyz") + shouldGiveOK(t, app, "/v2/customer/livez") + shouldGiveNotFound(t, app, "/v2/customer/readyz/") + shouldGiveNotFound(t, app, "/v2/customer/livez/") + shouldGiveNotFound(t, app, "/v3/todos/readyz") + shouldGiveNotFound(t, app, "/v3/todos/livez") + shouldGiveOK(t, app, "/v3/todos/readyz/") + shouldGiveOK(t, app, "/v3/todos/livez/") + shouldGiveNotFound(t, app, "/notDefined/readyz") + shouldGiveNotFound(t, app, "/notDefined/livez") + shouldGiveNotFound(t, app, "/notDefined/readyz/") + shouldGiveNotFound(t, app, "/notDefined/livez/") +} + func Test_HealthCheck_Default(t *testing.T) { t.Parallel() app := fiber.New() app.Use(New()) - req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/readyz", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) - - req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + shouldGiveOK(t, app, "/readyz") + shouldGiveOK(t, app, "/livez") + shouldGiveOK(t, app, "/readyz/") + shouldGiveOK(t, app, "/livez/") + shouldGiveNotFound(t, app, "/notDefined/readyz") + shouldGiveNotFound(t, app, "/notDefined/livez") } func Test_HealthCheck_Custom(t *testing.T) { @@ -31,11 +123,6 @@ func Test_HealthCheck_Custom(t *testing.T) { app := fiber.New() c1 := make(chan struct{}, 1) - go func() { - time.Sleep(1 * time.Second) - c1 <- struct{}{} - }() - app.Use(New(Config{ LivenessProbe: func(c *fiber.Ctx) bool { return true @@ -53,12 +140,9 @@ func Test_HealthCheck_Custom(t *testing.T) { })) // Live should return 200 with GET request - req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/live", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) - + shouldGiveOK(t, app, "/live") // Live should return 404 with POST request - req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) + req, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) @@ -68,16 +152,53 @@ func Test_HealthCheck_Custom(t *testing.T) { utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 503 with GET request before the channel is closed - req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusServiceUnavailable, req.StatusCode) - - time.Sleep(1 * time.Second) + shouldGiveStatus(t, app, "/ready", fiber.StatusServiceUnavailable) // Ready should return 200 with GET request after the channel is closed - req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/ready", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusOK, req.StatusCode) + c1 <- struct{}{} + shouldGiveOK(t, app, "/ready") +} + +func Test_HealthCheck_Custom_Nested(t *testing.T) { + t.Parallel() + + app := fiber.New() + + c1 := make(chan struct{}, 1) + + app.Use(New(Config{ + LivenessProbe: func(c *fiber.Ctx) bool { + return true + }, + LivenessEndpoint: "/probe/live", + ReadinessProbe: func(c *fiber.Ctx) bool { + select { + case <-c1: + return true + default: + return false + } + }, + ReadinessEndpoint: "/probe/ready", + })) + + shouldGiveOK(t, app, "/probe/live") + shouldGiveStatus(t, app, "/probe/ready", fiber.StatusServiceUnavailable) + shouldGiveOK(t, app, "/probe/live/") + shouldGiveStatus(t, app, "/probe/ready/", fiber.StatusServiceUnavailable) + shouldGiveNotFound(t, app, "/probe/livez") + shouldGiveNotFound(t, app, "/probe/readyz") + shouldGiveNotFound(t, app, "/probe/livez/") + shouldGiveNotFound(t, app, "/probe/readyz/") + shouldGiveNotFound(t, app, "/livez") + shouldGiveNotFound(t, app, "/readyz") + shouldGiveNotFound(t, app, "/readyz/") + shouldGiveNotFound(t, app, "/livez/") + + c1 <- struct{}{} + shouldGiveOK(t, app, "/probe/ready") + c1 <- struct{}{} + shouldGiveOK(t, app, "/probe/ready/") } func Test_HealthCheck_Next(t *testing.T) { @@ -91,9 +212,8 @@ func Test_HealthCheck_Next(t *testing.T) { }, })) - req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) - utils.AssertEqual(t, nil, err) - utils.AssertEqual(t, fiber.StatusNotFound, req.StatusCode) + shouldGiveNotFound(t, app, "/readyz") + shouldGiveNotFound(t, app, "/livez") } func Benchmark_HealthCheck(b *testing.B) { From 2048c75cc0dd9842a4ba7835c4aefb465cfb07ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Wed, 21 Feb 2024 09:58:52 +0100 Subject: [PATCH 31/51] merge v2 in v3 --- .github/workflows/benchmark.yml | 3 ++- .github/workflows/codeql-analysis.yml | 3 ++- .github/workflows/linter.yml | 3 ++- .github/workflows/release-drafter.yml | 3 ++- .github/workflows/sync-docs.yml | 11 ++++++----- .github/workflows/test.yml | 3 ++- .github/workflows/vulncheck.yml | 3 ++- ctx_test.go | 4 ++-- docs/api/middleware/logger.md | 2 +- middleware/healthcheck/healthcheck_test.go | 1 - middleware/logger/logger_test.go | 6 +++--- 11 files changed, 24 insertions(+), 18 deletions(-) diff --git a/.github/workflows/benchmark.yml b/.github/workflows/benchmark.yml index 934597779d..a4229ce993 100644 --- a/.github/workflows/benchmark.yml +++ b/.github/workflows/benchmark.yml @@ -1,7 +1,8 @@ on: push: branches: - - v2 + - master + - main paths: - "**" - "!docs/**" diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml index 0476abfba2..82036cc967 100644 --- a/.github/workflows/codeql-analysis.yml +++ b/.github/workflows/codeql-analysis.yml @@ -3,7 +3,8 @@ name: "CodeQL" on: push: branches: - - v2 + - master + - main paths: - "**" - "!docs/**" diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 123bd5b72c..188a68291e 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -4,7 +4,8 @@ name: golangci-lint on: push: branches: - - v2 + - master + - main pull_request: permissions: diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml index 898049c404..601dd98937 100644 --- a/.github/workflows/release-drafter.yml +++ b/.github/workflows/release-drafter.yml @@ -4,7 +4,8 @@ on: push: # branches to consider in the event; optional, defaults to all branches: - - v2 + - master + - main jobs: update_release_draft: diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index dd53569b2e..eb35d75bd2 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -1,11 +1,12 @@ name: "Sync docs" on: -# push: -# branches: -# - v2 -# paths: -# - "docs/**" + push: + branches: + - master + - main + paths: + - "docs/**" release: types: [published] diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9a0842b569..276cb6563d 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,7 +1,8 @@ on: push: branches: - - v2 + - master + - main paths: - "**" - "!docs/**" diff --git a/.github/workflows/vulncheck.yml b/.github/workflows/vulncheck.yml index f28ab5b0e2..e6d29ccb4b 100644 --- a/.github/workflows/vulncheck.yml +++ b/.github/workflows/vulncheck.yml @@ -3,7 +3,8 @@ name: Run govulncheck on: push: branches: - - v2 + - master + - main paths: - "**" - "!docs/**" diff --git a/ctx_test.go b/ctx_test.go index e9a7ccd150..b5ee60dc75 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1362,8 +1362,8 @@ func Test_Ctx_Parsers(t *testing.T) { type TestStruct struct { Name string Class int - NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" reqHeader:"name2"` - ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" reqHeader:"class2"` + NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" header:"name2"` + ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" header:"class2"` } withValues := func(t *testing.T, actionFn func(c Ctx, testStruct *TestStruct) error) { diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index 41f399ad2d..7c147ba0dd 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -116,7 +116,7 @@ Writing to os.File is goroutine-safe, but if you are using a custom Output that var ConfigDefault = Config{ Next: nil, Done: nil, - Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n", + Format: "[${time}] ${ip} ${status} - ${latency} ${method} ${path} ${error}\n", TimeFormat: "15:04:05", TimeZone: "Local", TimeInterval: 500 * time.Millisecond, diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index 3d1173a302..75651178cc 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -18,7 +18,6 @@ func Test_HealthCheck_Default(t *testing.T) { req, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/readyz", nil)) require.NoError(t, err) - require.NoError(t, err) require.Equal(t, fiber.StatusOK, req.StatusCode) req, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/livez", nil)) diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index 4ab821c32d..6e2dbaa0a0 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -147,7 +147,7 @@ type fakeErrorOutput int func (o *fakeErrorOutput) Write([]byte) (int, error) { *o++ - return 0, nil + return 0, errors.New("fake output") } // go test -run Test_Logger_ErrorOutput_WithoutColor @@ -163,7 +163,7 @@ func Test_Logger_ErrorOutput_WithoutColor(t *testing.T) { resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) - require.EqualValues(t, 2, *o) + require.EqualValues(t, 1, *o) } // go test -run Test_Logger_ErrorOutput @@ -178,7 +178,7 @@ func Test_Logger_ErrorOutput(t *testing.T) { resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) - require.EqualValues(t, 2, *o) + require.EqualValues(t, 1, *o) } // go test -run Test_Logger_All From f0cd3b44b086544a37886232d0530601f2406c23 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Wed, 21 Feb 2024 08:47:33 -0500 Subject: [PATCH 32/51] Merge pull request from GHSA-fmg4-x8pw-hjhg MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Enforce Wildcard Origins with AllowCredentials check * Expand unit-tests, fix issues with subdomains logic, update docs * Update cors.md * Added test using localhost, ipv4, and ipv6 address * improve documentation markdown --------- Co-authored-by: René Werner --- docs/api/middleware/cors.md | 31 ++++--- middleware/cors/cors.go | 61 ++++++++++---- middleware/cors/cors_test.go | 154 ++++++++++++++++++++++++++++------ middleware/cors/utils.go | 99 ++++++++++++++-------- middleware/cors/utils_test.go | 145 ++++++++++++++++++++++++++++++++ 5 files changed, 402 insertions(+), 88 deletions(-) create mode 100644 middleware/cors/utils_test.go diff --git a/docs/api/middleware/cors.md b/docs/api/middleware/cors.md index 9a28342fd3..ca250833d6 100644 --- a/docs/api/middleware/cors.md +++ b/docs/api/middleware/cors.md @@ -10,6 +10,8 @@ The middleware conforms to the `access-control-allow-origin` specification by pa For more control, `AllowOriginsFunc` can be used to programatically determine if an origin is allowed. If no match was found in `AllowOrigins` and if `AllowOriginsFunc` returns true then the 'access-control-allow-origin' response header is set to the 'origin' request header. +When defining your Origins make sure they are properly formatted. The middleware validates and normalizes the provided origins, ensuring they're in the correct format by checking for valid schemes (http or https), and removing any trailing slashes. + ## Signatures ```go @@ -56,18 +58,27 @@ app.Use(cors.New(cors.Config{ })) ``` +**Note: The following configuration is considered insecure and will result in a panic.** + +```go +app.Use(cors.New(cors.Config{ + AllowOrigins: "*", + AllowCredentials: true, +})) +``` + ## Config -| Property | Type | Description | Default | -|:-----------------|:---------------------------|:----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------| -| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | -| AllowOriginsFunc | `func(origin string) bool` | AllowOriginsFunc defines a function that will set the 'access-control-allow-origin' response header to the 'origin' request header when returned true. | `nil` | -| AllowOrigins | `string` | AllowOrigin defines a comma separated list of origins that may access the resource. | `"*"` | -| AllowMethods | `string` | AllowMethods defines a list of methods allowed when accessing the resource. This is used in response to a preflight request. | `"GET,POST,HEAD,PUT,DELETE,PATCH"` | -| AllowHeaders | `string` | AllowHeaders defines a list of request headers that can be used when making the actual request. This is in response to a preflight request. | `""` | -| AllowCredentials | `bool` | AllowCredentials indicates whether or not the response to the request can be exposed when the credentials flag is true. | `false` | -| ExposeHeaders | `string` | ExposeHeaders defines a whitelist headers that clients are allowed to access. | `""` | -| MaxAge | `int` | MaxAge indicates how long (in seconds) the results of a preflight request can be cached. If you pass MaxAge 0, Access-Control-Max-Age header will not be added and browser will use 5 seconds by default. To disable caching completely, pass MaxAge value negative. It will set the Access-Control-Max-Age header 0. | `0` | +| Property | Type | Description | Default | +|:-----------------|:---------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:-----------------------------------| +| Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | +| AllowOriginsFunc | `func(origin string) bool` | AllowOriginsFunc defines a function that will set the 'access-control-allow-origin' response header to the 'origin' request header when returned true. This allows for dynamic evaluation of allowed origins. Note if AllowCredentials is true, wildcard origins will be not have the 'access-control-allow-credentials' header set to 'true'. | `nil` | +| AllowOrigins | `string` | AllowOrigin defines a comma separated list of origins that may access the resource. | `"*"` | +| AllowMethods | `string` | AllowMethods defines a list of methods allowed when accessing the resource. This is used in response to a preflight request. | `"GET,POST,HEAD,PUT,DELETE,PATCH"` | +| AllowHeaders | `string` | AllowHeaders defines a list of request headers that can be used when making the actual request. This is in response to a preflight request. | `""` | +| AllowCredentials | `bool` | AllowCredentials indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials. Note: If true, AllowOrigins cannot be set to a wildcard ("*") to prevent security vulnerabilities. | `false` | +| ExposeHeaders | `string` | ExposeHeaders defines a whitelist headers that clients are allowed to access. | `""` | +| MaxAge | `int` | MaxAge indicates how long (in seconds) the results of a preflight request can be cached. If you pass MaxAge 0, Access-Control-Max-Age header will not be added and browser will use 5 seconds by default. To disable caching completely, pass MaxAge value negative. It will set the Access-Control-Max-Age header 0. | `0` | ## Default Config diff --git a/middleware/cors/cors.go b/middleware/cors/cors.go index ebc1c6b1cb..2ca3767d1f 100644 --- a/middleware/cors/cors.go +++ b/middleware/cors/cors.go @@ -16,12 +16,14 @@ type Config struct { Next func(c *fiber.Ctx) bool // AllowOriginsFunc defines a function that will set the 'access-control-allow-origin' - // response header to the 'origin' request header when returned true. + // response header to the 'origin' request header when returned true. This allows for + // dynamic evaluation of allowed origins. Note if AllowCredentials is true, wildcard origins + // will be not have the 'access-control-allow-credentials' header set to 'true'. // // Optional. Default: nil AllowOriginsFunc func(origin string) bool - // AllowOrigin defines a list of origins that may access the resource. + // AllowOrigin defines a comma separated list of origins that may access the resource. // // Optional. Default value "*" AllowOrigins string @@ -41,7 +43,8 @@ type Config struct { // AllowCredentials indicates whether or not the response to the request // can be exposed when the credentials flag is true. When used as part of // a response to a preflight request, this indicates whether or not the - // actual request can be made using credentials. + // actual request can be made using credentials. Note: If true, AllowOrigins + // cannot be set to a wildcard ("*") to prevent security vulnerabilities. // // Optional. Default value false. AllowCredentials bool @@ -105,6 +108,26 @@ func New(config ...Config) fiber.Handler { log.Warn("[CORS] Both 'AllowOrigins' and 'AllowOriginsFunc' have been defined.") } + // Validate CORS credentials configuration + if cfg.AllowCredentials && cfg.AllowOrigins == "*" { + panic("[CORS] Insecure setup, 'AllowCredentials' is set to true, and 'AllowOrigins' is set to a wildcard.") + } + + // Validate and normalize static AllowOrigins if not using AllowOriginsFunc + if cfg.AllowOriginsFunc == nil && cfg.AllowOrigins != "" && cfg.AllowOrigins != "*" { + validatedOrigins := []string{} + for _, origin := range strings.Split(cfg.AllowOrigins, ",") { + isValid, normalizedOrigin := normalizeOrigin(origin) + if isValid { + validatedOrigins = append(validatedOrigins, normalizedOrigin) + } else { + log.Warnf("[CORS] Invalid origin format in configuration: %s", origin) + panic("[CORS] Invalid origin provided in configuration") + } + } + cfg.AllowOrigins = strings.Join(validatedOrigins, ",") + } + // Convert string to slice allowOrigins := strings.Split(strings.ReplaceAll(cfg.AllowOrigins, " ", ""), ",") @@ -123,22 +146,18 @@ func New(config ...Config) fiber.Handler { return c.Next() } - // Get origin header - origin := c.Get(fiber.HeaderOrigin) + // Get originHeader header + originHeader := c.Get(fiber.HeaderOrigin) allowOrigin := "" // Check allowed origins - for _, o := range allowOrigins { - if o == "*" { + for _, origin := range allowOrigins { + if origin == "*" { allowOrigin = "*" break } - if o == origin { - allowOrigin = o - break - } - if matchSubdomain(origin, o) { - allowOrigin = origin + if validateDomain(originHeader, origin) { + allowOrigin = originHeader break } } @@ -147,8 +166,8 @@ func New(config ...Config) fiber.Handler { // handling the value in 'AllowOrigins' does // not result in allowOrigin being set. if allowOrigin == "" && cfg.AllowOriginsFunc != nil { - if cfg.AllowOriginsFunc(origin) { - allowOrigin = origin + if cfg.AllowOriginsFunc(originHeader) { + allowOrigin = originHeader } } @@ -173,9 +192,17 @@ func New(config ...Config) fiber.Handler { c.Set(fiber.HeaderAccessControlAllowOrigin, allowOrigin) c.Set(fiber.HeaderAccessControlAllowMethods, allowMethods) - // Set Allow-Credentials if set to true if cfg.AllowCredentials { - c.Set(fiber.HeaderAccessControlAllowCredentials, "true") + // When AllowCredentials is true, set the Access-Control-Allow-Origin to the specific origin instead of '*' + if allowOrigin != "*" && allowOrigin != "" { + c.Set(fiber.HeaderAccessControlAllowOrigin, allowOrigin) + c.Set(fiber.HeaderAccessControlAllowCredentials, "true") + } else if allowOrigin == "*" { + log.Warn("[CORS] 'AllowCredentials' is true, but 'AllowOrigins' cannot be set to '*'.") + } + } else { + // For non-credential requests, it's safe to set to '*' or specific origins + c.Set(fiber.HeaderAccessControlAllowOrigin, allowOrigin) } // Set Allow-Headers if not empty diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 22fef8442b..9fc2852556 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -35,7 +35,7 @@ func Test_CORS_Negative_MaxAge(t *testing.T) { ctx := &fasthttp.RequestCtx{} ctx.Request.Header.SetMethod(fiber.MethodOptions) - ctx.Request.Header.Set(fiber.HeaderOrigin, "localhost") + ctx.Request.Header.Set(fiber.HeaderOrigin, "http://localhost") app.Handler()(ctx) utils.AssertEqual(t, "0", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlMaxAge))) @@ -72,7 +72,46 @@ func Test_CORS_Wildcard(t *testing.T) { app := fiber.New() // OPTIONS (preflight) response headers when AllowOrigins is * app.Use(New(Config{ - AllowOrigins: "*", + AllowOrigins: "*", + MaxAge: 3600, + ExposeHeaders: "X-Request-ID", + AllowHeaders: "Authentication", + })) + // Get handler pointer + handler := app.Handler() + + // Make request + ctx := &fasthttp.RequestCtx{} + ctx.Request.SetRequestURI("/") + ctx.Request.Header.Set(fiber.HeaderOrigin, "http://localhost") + ctx.Request.Header.SetMethod(fiber.MethodOptions) + + // Perform request + handler(ctx) + + // Check result + utils.AssertEqual(t, "*", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) // Validates request is not reflecting origin in the response + utils.AssertEqual(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) + utils.AssertEqual(t, "3600", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlMaxAge))) + utils.AssertEqual(t, "Authentication", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowHeaders))) + + // Test non OPTIONS (preflight) response headers + ctx = &fasthttp.RequestCtx{} + ctx.Request.Header.SetMethod(fiber.MethodGet) + handler(ctx) + + utils.AssertEqual(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) + utils.AssertEqual(t, "X-Request-ID", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlExposeHeaders))) +} + +// go test -run -v Test_CORS_Origin_AllowCredentials +func Test_CORS_Origin_AllowCredentials(t *testing.T) { + t.Parallel() + // New fiber instance + app := fiber.New() + // OPTIONS (preflight) response headers when AllowOrigins is * + app.Use(New(Config{ + AllowOrigins: "http://localhost", AllowCredentials: true, MaxAge: 3600, ExposeHeaders: "X-Request-ID", @@ -84,14 +123,14 @@ func Test_CORS_Wildcard(t *testing.T) { // Make request ctx := &fasthttp.RequestCtx{} ctx.Request.SetRequestURI("/") - ctx.Request.Header.Set(fiber.HeaderOrigin, "localhost") + ctx.Request.Header.Set(fiber.HeaderOrigin, "http://localhost") ctx.Request.Header.SetMethod(fiber.MethodOptions) // Perform request handler(ctx) // Check result - utils.AssertEqual(t, "*", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) + utils.AssertEqual(t, "http://localhost", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) utils.AssertEqual(t, "true", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) utils.AssertEqual(t, "3600", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlMaxAge))) utils.AssertEqual(t, "Authentication", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowHeaders))) @@ -105,6 +144,57 @@ func Test_CORS_Wildcard(t *testing.T) { utils.AssertEqual(t, "X-Request-ID", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlExposeHeaders))) } +// go test -run -v Test_CORS_Wildcard_AllowCredentials_Panic +// Test for fiber-ghsa-fmg4-x8pw-hjhg +func Test_CORS_Wildcard_AllowCredentials_Panic(t *testing.T) { + t.Parallel() + // New fiber instance + app := fiber.New() + + didPanic := false + func() { + defer func() { + if r := recover(); r != nil { + didPanic = true + } + }() + + app.Use(New(Config{ + AllowOrigins: "*", + AllowCredentials: true, + })) + }() + + if !didPanic { + t.Errorf("Expected a panic when AllowOrigins is '*' and AllowCredentials is true") + } +} + +// go test -run -v Test_CORS_Invalid_Origin_Panic +func Test_CORS_Invalid_Origin_Panic(t *testing.T) { + t.Parallel() + // New fiber instance + app := fiber.New() + + didPanic := false + func() { + defer func() { + if r := recover(); r != nil { + didPanic = true + } + }() + + app.Use(New(Config{ + AllowOrigins: "localhost", + AllowCredentials: true, + })) + }() + + if !didPanic { + t.Errorf("Expected a panic when Origin is missing scheme") + } +} + // go test -run -v Test_CORS_Subdomain func Test_CORS_Subdomain(t *testing.T) { t.Parallel() @@ -193,12 +283,9 @@ func Test_CORS_AllowOriginScheme(t *testing.T) { shouldAllowOrigin: false, }, { - pattern: "http://*.example.com", - reqOrigin: `http://1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ - .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ - .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890\ - .1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.example.com`, - shouldAllowOrigin: false, + pattern: "http://*.example.com", + reqOrigin: "http://1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.1234567890.example.com", + shouldAllowOrigin: true, }, { pattern: "http://example.com", @@ -471,12 +558,13 @@ func Test_CORS_AllowOriginsAndAllowOriginsFunc_AllUseCases(t *testing.T) { } // The fix for issue #2422 -func Test_CORS_AllowCredetials(t *testing.T) { +func Test_CORS_AllowCredentials(t *testing.T) { testCases := []struct { - Name string - Config Config - RequestOrigin string - ResponseOrigin string + Name string + Config Config + RequestOrigin string + ResponseOrigin string + ResponseCredentials string }{ { Name: "AllowOriginsFuncDefined", @@ -488,19 +576,35 @@ func Test_CORS_AllowCredetials(t *testing.T) { }, RequestOrigin: "http://aaa.com", // The AllowOriginsFunc config was defined, should use the real origin of the function - ResponseOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + ResponseCredentials: "true", }, { - Name: "AllowOriginsFuncNotDefined", + Name: "fiber-ghsa-fmg4-x8pw-hjhg-wildcard-credentials", Config: Config{ AllowCredentials: true, + AllowOriginsFunc: func(origin string) bool { + return true + }, + }, + RequestOrigin: "*", + ResponseOrigin: "*", + // Middleware will validate that wildcard wont set credentials to true + ResponseCredentials: "", + }, + { + Name: "AllowOriginsFuncNotDefined", + Config: Config{ + // Setting this to true will cause the middleware to panic since default AllowOrigins is "*" + AllowCredentials: false, }, RequestOrigin: "http://aaa.com", // None of the AllowOrigins or AllowOriginsFunc config was defined, should use the default origin of "*" // which will cause the CORS error in the client: // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' // when the request's credentials mode is 'include'. - ResponseOrigin: "*", + ResponseOrigin: "*", + ResponseCredentials: "", }, { Name: "AllowOriginsDefined", @@ -508,8 +612,9 @@ func Test_CORS_AllowCredetials(t *testing.T) { AllowCredentials: true, AllowOrigins: "http://aaa.com", }, - RequestOrigin: "http://aaa.com", - ResponseOrigin: "http://aaa.com", + RequestOrigin: "http://aaa.com", + ResponseOrigin: "http://aaa.com", + ResponseCredentials: "true", }, { Name: "AllowOriginsDefined/UnallowedOrigin", @@ -517,8 +622,9 @@ func Test_CORS_AllowCredetials(t *testing.T) { AllowCredentials: true, AllowOrigins: "http://aaa.com", }, - RequestOrigin: "http://bbb.com", - ResponseOrigin: "", + RequestOrigin: "http://bbb.com", + ResponseOrigin: "", + ResponseCredentials: "", }, } @@ -536,9 +642,7 @@ func Test_CORS_AllowCredetials(t *testing.T) { handler(ctx) - if tc.Config.AllowCredentials { - utils.AssertEqual(t, "true", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) - } + utils.AssertEqual(t, tc.ResponseCredentials, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) utils.AssertEqual(t, tc.ResponseOrigin, string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) }) } diff --git a/middleware/cors/utils.go b/middleware/cors/utils.go index 8b6114bdab..313a430c77 100644 --- a/middleware/cors/utils.go +++ b/middleware/cors/utils.go @@ -1,56 +1,83 @@ package cors import ( + "net/url" "strings" ) +// matchScheme compares the scheme of the domain and pattern func matchScheme(domain, pattern string) bool { didx := strings.Index(domain, ":") pidx := strings.Index(pattern, ":") return didx != -1 && pidx != -1 && domain[:didx] == pattern[:pidx] } -// matchSubdomain compares authority with wildcard -func matchSubdomain(domain, pattern string) bool { - if !matchScheme(domain, pattern) { - return false +// validateDomain checks if the domain matches the pattern +func validateDomain(domain, pattern string) bool { + // Directly compare the domain and pattern for an exact match. + if domain == pattern { + return true } - didx := strings.Index(domain, "://") - pidx := strings.Index(pattern, "://") - if didx == -1 || pidx == -1 { - return false + + // Normalize domain and pattern to exclude schemes and ports for matching purposes + normalizedDomain := normalizeDomain(domain) + normalizedPattern := normalizeDomain(pattern) + + // Handling the case where pattern is a wildcard subdomain pattern. + if strings.HasPrefix(normalizedPattern, "*.") { + // Trim leading "*." from pattern for comparison. + trimmedPattern := normalizedPattern[2:] + + // Check if the domain ends with the trimmed pattern. + if strings.HasSuffix(normalizedDomain, trimmedPattern) { + // Ensure that the domain is not exactly the base domain. + if normalizedDomain != trimmedPattern { + // Special handling to prevent "example.com" matching "*.example.com". + if strings.TrimSuffix(normalizedDomain, trimmedPattern) != "" { + return true + } + } + } } - domAuth := domain[didx+3:] - // to avoid long loop by invalid long domain - const maxDomainLen = 253 - if len(domAuth) > maxDomainLen { - return false + + return false +} + +// normalizeDomain removes the scheme and port from the input domain +func normalizeDomain(input string) string { + // Remove scheme + input = strings.TrimPrefix(strings.TrimPrefix(input, "http://"), "https://") + + // Find and remove port, if present + if portIndex := strings.Index(input, ":"); portIndex != -1 { + input = input[:portIndex] } - patAuth := pattern[pidx+3:] - - domComp := strings.Split(domAuth, ".") - patComp := strings.Split(patAuth, ".") - const divHalf = 2 - for i := len(domComp)/divHalf - 1; i >= 0; i-- { - opp := len(domComp) - 1 - i - domComp[i], domComp[opp] = domComp[opp], domComp[i] + + return input +} + +// normalizeOrigin checks if the provided origin is in a correct format +// and normalizes it by removing any path or trailing slash. +// It returns a boolean indicating whether the origin is valid +// and the normalized origin. +func normalizeOrigin(origin string) (bool, string) { + parsedOrigin, err := url.Parse(origin) + if err != nil { + return false, "" } - for i := len(patComp)/divHalf - 1; i >= 0; i-- { - opp := len(patComp) - 1 - i - patComp[i], patComp[opp] = patComp[opp], patComp[i] + + // Validate the scheme is either http or https + if parsedOrigin.Scheme != "http" && parsedOrigin.Scheme != "https" { + return false, "" } - for i, v := range domComp { - if len(patComp) <= i { - return false - } - p := patComp[i] - if p == "*" { - return true - } - if p != v { - return false - } + // Validate there is a host present. The presence of a path, query, or fragment components + // is checked, but a trailing "/" (indicative of the root) is allowed for the path and will be normalized + if parsedOrigin.Host == "" || (parsedOrigin.Path != "" && parsedOrigin.Path != "/") || parsedOrigin.RawQuery != "" || parsedOrigin.Fragment != "" { + return false, "" } - return false + + // Normalize the origin by constructing it from the scheme and host. + // The path or trailing slash is not included in the normalized origin. + return true, strings.ToLower(parsedOrigin.Scheme) + "://" + strings.ToLower(parsedOrigin.Host) } diff --git a/middleware/cors/utils_test.go b/middleware/cors/utils_test.go new file mode 100644 index 0000000000..3acd692521 --- /dev/null +++ b/middleware/cors/utils_test.go @@ -0,0 +1,145 @@ +package cors + +import ( + "testing" +) + +// go test -run -v Test_normalizeOrigin +func Test_normalizeOrigin(t *testing.T) { + testCases := []struct { + origin string + expectedValid bool + expectedOrigin string + }{ + {"http://example.com", true, "http://example.com"}, // Simple case should work. + {"http://example.com/", true, "http://example.com"}, // Trailing slash should be removed. + {"http://example.com:3000", true, "http://example.com:3000"}, // Port should be preserved. + {"http://example.com:3000/", true, "http://example.com:3000"}, // Trailing slash should be removed. + {"http://", false, ""}, // Invalid origin should not be accepted. + {"http://example.com/path", false, ""}, // Path should not be accepted. + {"http://example.com?query=123", false, ""}, // Query should not be accepted. + {"http://example.com#fragment", false, ""}, // Fragment should not be accepted. + {"http://localhost", true, "http://localhost"}, // Localhost should be accepted. + {"http://127.0.0.1", true, "http://127.0.0.1"}, // IPv4 address should be accepted. + {"http://[::1]", true, "http://[::1]"}, // IPv6 address should be accepted. + {"http://[::1]:8080", true, "http://[::1]:8080"}, // IPv6 address with port should be accepted. + {"http://[::1]:8080/", true, "http://[::1]:8080"}, // IPv6 address with port and trailing slash should be accepted. + {"http://[::1]:8080/path", false, ""}, // IPv6 address with port and path should not be accepted. + {"http://[::1]:8080?query=123", false, ""}, // IPv6 address with port and query should not be accepted. + {"http://[::1]:8080#fragment", false, ""}, // IPv6 address with port and fragment should not be accepted. + {"http://[::1]:8080/path?query=123#fragment", false, ""}, // IPv6 address with port, path, query, and fragment should not be accepted. + {"http://[::1]:8080/path?query=123#fragment/", false, ""}, // IPv6 address with port, path, query, fragment, and trailing slash should not be accepted. + {"http://[::1]:8080/path?query=123#fragment/invalid", false, ""}, // IPv6 address with port, path, query, fragment, trailing slash, and invalid segment should not be accepted. + {"http://[::1]:8080/path?query=123#fragment/invalid/", false, ""}, // IPv6 address with port, path, query, fragment, trailing slash, and invalid segment with trailing slash should not be accepted. + {"http://[::1]:8080/path?query=123#fragment/invalid/segment", false, ""}, // IPv6 address with port, path, query, fragment, trailing slash, and invalid segment with additional segment should not be accepted. + } + + for _, tc := range testCases { + valid, normalizedOrigin := normalizeOrigin(tc.origin) + + if valid != tc.expectedValid { + t.Errorf("Expected origin '%s' to be valid: %v, but got: %v", tc.origin, tc.expectedValid, valid) + } + + if normalizedOrigin != tc.expectedOrigin { + t.Errorf("Expected normalized origin '%s' for origin '%s', but got: '%s'", tc.expectedOrigin, tc.origin, normalizedOrigin) + } + } +} + +// go test -run -v Test_matchScheme +func Test_matchScheme(t *testing.T) { + testCases := []struct { + domain string + pattern string + expected bool + }{ + {"http://example.com", "http://example.com", true}, // Exact match should work. + {"https://example.com", "http://example.com", false}, // Scheme mismatch should matter. + {"http://example.com", "https://example.com", false}, // Scheme mismatch should matter. + {"http://example.com", "http://example.org", true}, // Different domains should not matter. + {"http://example.com", "http://example.com:8080", true}, // Port should not matter. + {"http://example.com:8080", "http://example.com", true}, // Port should not matter. + {"http://example.com:8080", "http://example.com:8081", true}, // Different ports should not matter. + {"http://localhost", "http://localhost", true}, // Localhost should match. + {"http://127.0.0.1", "http://127.0.0.1", true}, // IPv4 address should match. + {"http://[::1]", "http://[::1]", true}, // IPv6 address should match. + } + + for _, tc := range testCases { + result := matchScheme(tc.domain, tc.pattern) + + if result != tc.expected { + t.Errorf("Expected matchScheme('%s', '%s') to be %v, but got %v", tc.domain, tc.pattern, tc.expected, result) + } + } +} + +// go test -run -v Test_validateOrigin +func Test_validateOrigin(t *testing.T) { + testCases := []struct { + domain string + pattern string + expected bool + }{ + {"http://example.com", "http://example.com", true}, // Exact match should work. + {"https://example.com", "http://example.com", false}, // Scheme mismatch should matter in CORS context. + {"http://example.com", "https://example.com", false}, // Scheme mismatch should matter in CORS context. + {"http://example.com", "http://example.org", false}, // Different domains should not match. + {"http://example.com", "http://example.com:8080", false}, // Port mismatch should matter. + {"http://example.com:8080", "http://example.com", false}, // Port mismatch should matter. + {"http://example.com:8080", "http://example.com:8081", false}, // Different ports should not match. + {"example.com", "example.com", true}, // Simplified form, assuming scheme and port are not considered here, but in practice, they are part of the origin. + {"sub.example.com", "example.com", false}, // Subdomain should not match the base domain directly. + {"sub.example.com", "*.example.com", true}, // Correct assumption for wildcard subdomain matching. + {"example.com", "*.example.com", false}, // Base domain should not match its wildcard subdomain pattern. + {"sub.example.com", "*.com", true}, // Technically correct for pattern matching, but broad wildcard use like this is not recommended for CORS. + {"sub.sub.example.com", "*.example.com", true}, // Nested subdomain should match the wildcard pattern. + {"example.com", "*.org", false}, // Different TLDs should not match. + {"example.com", "example.org", false}, // Different domains should not match. + {"example.com:8080", "*.example.com", false}, // Different ports mean different origins. + {"example.com", "sub.example.net", false}, // Different domains should not match. + {"http://localhost", "http://localhost", true}, // Localhost should match. + {"http://127.0.0.1", "http://127.0.0.1", true}, // IPv4 address should match. + {"http://[::1]", "http://[::1]", true}, // IPv6 address should match. + } + + for _, tc := range testCases { + result := validateDomain(tc.domain, tc.pattern) + + if result != tc.expected { + t.Errorf("Expected validateOrigin('%s', '%s') to be %v, but got %v", tc.domain, tc.pattern, tc.expected, result) + } + } +} + +// go test -run -v Test_normalizeDomain +func Test_normalizeDomain(t *testing.T) { + testCases := []struct { + input string + expectedOutput string + }{ + {"http://example.com", "example.com"}, // Simple case with http scheme. + {"https://example.com", "example.com"}, // Simple case with https scheme. + {"http://example.com:3000", "example.com"}, // Case with port. + {"https://example.com:3000", "example.com"}, // Case with port and https scheme. + {"http://example.com/path", "example.com/path"}, // Case with path. + {"http://example.com?query=123", "example.com?query=123"}, // Case with query. + {"http://example.com#fragment", "example.com#fragment"}, // Case with fragment. + {"example.com", "example.com"}, // Case without scheme. + {"example.com:8080", "example.com"}, // Case without scheme but with port. + {"sub.example.com", "sub.example.com"}, // Case with subdomain. + {"sub.sub.example.com", "sub.sub.example.com"}, // Case with nested subdomain. + {"http://localhost", "localhost"}, // Case with localhost. + {"http://127.0.0.1", "127.0.0.1"}, // Case with IPv4 address. + {"http://[::1]", "[::1]"}, // Case with IPv6 address. + } + + for _, tc := range testCases { + output := normalizeDomain(tc.input) + + if output != tc.expectedOutput { + t.Errorf("Expected normalized domain '%s' for input '%s', but got: '%s'", tc.expectedOutput, tc.input, output) + } + } +} From f9fcb0297c942a84465d522a4e6487f04a372abb Mon Sep 17 00:00:00 2001 From: RW Date: Wed, 21 Feb 2024 17:03:00 +0100 Subject: [PATCH 33/51] Update app.go prepare release v2.52.1 --- app.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.go b/app.go index 2ce88704c5..23501437b1 100644 --- a/app.go +++ b/app.go @@ -30,7 +30,7 @@ import ( ) // Version of current fiber package -const Version = "2.52.0" +const Version = "2.52.1" // Handler defines a function to serve HTTP requests. type Handler = func(*Ctx) error From 70f21d5f7eb486875d6f6f07c858c7d20e9b3f0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Wed, 21 Feb 2024 21:18:56 +0100 Subject: [PATCH 34/51] fix cors domain normalize --- middleware/cors/utils.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/middleware/cors/utils.go b/middleware/cors/utils.go index 313a430c77..d1280899c9 100644 --- a/middleware/cors/utils.go +++ b/middleware/cors/utils.go @@ -49,8 +49,10 @@ func normalizeDomain(input string) string { input = strings.TrimPrefix(strings.TrimPrefix(input, "http://"), "https://") // Find and remove port, if present - if portIndex := strings.Index(input, ":"); portIndex != -1 { - input = input[:portIndex] + if len(input) > 0 && input[0] != '[' { + if portIndex := strings.Index(input, ":"); portIndex != -1 { + input = input[:portIndex] + } } return input From 0df0e0855ddaa0ab1d548d2d34b9e3ecaa1a6485 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Wed, 21 Feb 2024 21:43:28 +0100 Subject: [PATCH 35/51] fix sync-docs workflow --- .github/workflows/sync-docs.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index dd53569b2e..1a7076f7eb 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -1,11 +1,11 @@ name: "Sync docs" on: -# push: -# branches: -# - v2 -# paths: -# - "docs/**" + push: + branches: + - v2 + paths: + - "docs/**" release: types: [published] From f50b57b079ff985f3f58701cf02989e844ee5dfc Mon Sep 17 00:00:00 2001 From: Jason McNeil Date: Wed, 21 Feb 2024 16:46:48 -0400 Subject: [PATCH 36/51] test: fix failing tests --- ctx_test.go | 4 ++-- middleware/logger/logger_test.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ctx_test.go b/ctx_test.go index b5ee60dc75..97c1bb4f53 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1357,17 +1357,17 @@ func Benchmark_Ctx_Fresh_WithNoCache(b *testing.B) { func Test_Ctx_Parsers(t *testing.T) { t.Parallel() // setup - app := New() type TestStruct struct { Name string Class int - NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" header:"name2"` + NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" header:"name2"` ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" header:"class2"` } withValues := func(t *testing.T, actionFn func(c Ctx, testStruct *TestStruct) error) { t.Helper() + app := New() c := app.AcquireCtx() defer app.ReleaseCtx(c) testStruct := new(TestStruct) diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index 6e2dbaa0a0..2694e5112d 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -163,7 +163,7 @@ func Test_Logger_ErrorOutput_WithoutColor(t *testing.T) { resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) - require.EqualValues(t, 1, *o) + require.EqualValues(t, 2, *o) } // go test -run Test_Logger_ErrorOutput @@ -178,7 +178,7 @@ func Test_Logger_ErrorOutput(t *testing.T) { resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) - require.EqualValues(t, 1, *o) + require.EqualValues(t, 2, *o) } // go test -run Test_Logger_All From ddc6b231f816f197a5f1d73825eaf0c7d55b08f4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9=20Werner?= Date: Wed, 21 Feb 2024 21:54:55 +0100 Subject: [PATCH 37/51] fix sync-docs workflow --- .github/workflows/sync-docs.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/sync-docs.yml b/.github/workflows/sync-docs.yml index 1a7076f7eb..da5380b992 100644 --- a/.github/workflows/sync-docs.yml +++ b/.github/workflows/sync-docs.yml @@ -16,7 +16,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event.release.tag_name }} fetch-depth: 2 - name: Setup Node.js environment From 8d739f111d425b8b6cdf42a3a3514cea2ff70cde Mon Sep 17 00:00:00 2001 From: Jason McNeil Date: Wed, 21 Feb 2024 16:56:44 -0400 Subject: [PATCH 38/51] test: cors middleware use testify require --- middleware/cors/cors_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index e740a7c71d..5854fcdb2d 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -89,18 +89,18 @@ func Test_CORS_Wildcard(t *testing.T) { handler(ctx) // Check result - utils.AssertEqual(t, "*", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) // Validates request is not reflecting origin in the response - utils.AssertEqual(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) - utils.AssertEqual(t, "3600", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlMaxAge))) - utils.AssertEqual(t, "Authentication", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowHeaders))) + require.Equal(t, "*", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowOrigin))) // Validates request is not reflecting origin in the response + require.Equal(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) + require.Equal(t, "3600", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlMaxAge))) + require.Equal(t, "Authentication", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowHeaders))) // Test non OPTIONS (preflight) response headers ctx = &fasthttp.RequestCtx{} ctx.Request.Header.SetMethod(fiber.MethodGet) handler(ctx) - utils.AssertEqual(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) - utils.AssertEqual(t, "X-Request-ID", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlExposeHeaders))) + require.Equal(t, "", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials))) + require.Equal(t, "X-Request-ID", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlExposeHeaders))) } // go test -run -v Test_CORS_Origin_AllowCredentials From 7c805cd5ea3660f343b4c5e51c46da8d4afd8096 Mon Sep 17 00:00:00 2001 From: Jason McNeil Date: Wed, 21 Feb 2024 17:18:51 -0400 Subject: [PATCH 39/51] chore: fix lint warnings --- ctx_test.go | 4 ++-- middleware/cors/cors_test.go | 2 +- middleware/healthcheck/healthcheck.go | 2 +- middleware/healthcheck/healthcheck_test.go | 6 +++--- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ctx_test.go b/ctx_test.go index 97c1bb4f53..4bf3ad2a2c 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1361,8 +1361,8 @@ func Test_Ctx_Parsers(t *testing.T) { type TestStruct struct { Name string Class int - NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" header:"name2"` - ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" header:"class2"` + NameWithDefault string `json:"name2" xml:"Name2" form:"name2" cookie:"name2" query:"name2" params:"name2" header:"Name2"` + ClassWithDefault int `json:"class2" xml:"Class2" form:"class2" cookie:"class2" query:"class2" params:"class2" header:"Class2"` } withValues := func(t *testing.T, actionFn func(c Ctx, testStruct *TestStruct) error) { diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 5854fcdb2d..3d3ae8c655 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -582,7 +582,7 @@ func Test_CORS_AllowCredentials(t *testing.T) { Name: "fiber-ghsa-fmg4-x8pw-hjhg-wildcard-credentials", Config: Config{ AllowCredentials: true, - AllowOriginsFunc: func(origin string) bool { + AllowOriginsFunc: func(_ string) bool { return true }, }, diff --git a/middleware/healthcheck/healthcheck.go b/middleware/healthcheck/healthcheck.go index b114112a67..f4eeb75423 100644 --- a/middleware/healthcheck/healthcheck.go +++ b/middleware/healthcheck/healthcheck.go @@ -1,8 +1,8 @@ package healthcheck import ( - "github.com/gofiber/fiber/v3" "github.com/gofiber/fiber/v2/utils" + "github.com/gofiber/fiber/v3" ) // HealthChecker defines a function to check liveness or readiness of the application diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index 2a57cfcaa2..d3ec7bedac 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -1,8 +1,8 @@ package healthcheck import ( - "fmt" "net/http/httptest" + "strconv" "testing" "github.com/gofiber/fiber/v3" @@ -13,8 +13,8 @@ import ( func shouldGiveStatus(t *testing.T, app *fiber.App, path string, expectedStatus int) { t.Helper() req, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, nil)) - require.Equal(t, nil, err) - require.Equal(t, expectedStatus, req.StatusCode, "path: "+path+" should match "+fmt.Sprint(expectedStatus)) + require.NoError(t, err) + require.Equal(t, expectedStatus, req.StatusCode, "path: "+path+" should match "+strconv.Itoa(expectedStatus)) } func shouldGiveOK(t *testing.T, app *fiber.App, path string) { From cdaeb3bda1e41dc0f2d4689706858343e28f039a Mon Sep 17 00:00:00 2001 From: Jason McNeil Date: Wed, 21 Feb 2024 18:37:18 -0400 Subject: [PATCH 40/51] chore: revert test isolation. --- ctx_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ctx_test.go b/ctx_test.go index 4bf3ad2a2c..48c893efb4 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -1357,6 +1357,7 @@ func Benchmark_Ctx_Fresh_WithNoCache(b *testing.B) { func Test_Ctx_Parsers(t *testing.T) { t.Parallel() // setup + app := New() type TestStruct struct { Name string @@ -1367,7 +1368,7 @@ func Test_Ctx_Parsers(t *testing.T) { withValues := func(t *testing.T, actionFn func(c Ctx, testStruct *TestStruct) error) { t.Helper() - app := New() + c := app.AcquireCtx() defer app.ReleaseCtx(c) testStruct := new(TestStruct) From 5a0167a460ef2385ecade84683bd0007a28b97c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 12:46:15 +0100 Subject: [PATCH 41/51] fixed the fasthttp ctx race condition problem --- app.go | 6 +- app_test.go | 9 +- bind_test.go | 74 +++--- ctx_interface.go | 12 +- ctx_test.go | 408 ++++++++++++++--------------- go.mod | 2 - go.sum | 4 - middleware/adaptor/adaptor.go | 2 +- middleware/adaptor/adaptor_test.go | 2 +- middleware/csrf/csrf_test.go | 24 +- middleware/session/session_test.go | 32 +-- middleware/session/store_test.go | 10 +- redirect_test.go | 38 +-- router.go | 4 +- router_test.go | 5 +- 15 files changed, 311 insertions(+), 321 deletions(-) diff --git a/app.go b/app.go index f681ae2ce2..f51186fe7e 100644 --- a/app.go +++ b/app.go @@ -496,7 +496,7 @@ func New(config ...Config) *App { // Create Ctx pool app.pool = sync.Pool{ New: func() any { - return app.NewCtx(&fasthttp.RequestCtx{}) + return app.newCtx() }, } @@ -1071,9 +1071,7 @@ func (app *App) ErrorHandler(ctx Ctx, err error) error { // errors before calling the application's error handler method. func (app *App) serverErrorHandler(fctx *fasthttp.RequestCtx, err error) { // Acquire Ctx with fasthttp request from pool - c := app.AcquireCtx() - c.Reset(fctx) - + c := app.AcquireCtx(fctx) defer app.ReleaseCtx(c) var ( diff --git a/app_test.go b/app_test.go index 81d7650e44..46d05bd0d1 100644 --- a/app_test.go +++ b/app_test.go @@ -314,7 +314,7 @@ func Test_App_serverErrorHandler_Internal_Error(t *testing.T) { t.Parallel() app := New() msg := "test err" - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed app.serverErrorHandler(c.fasthttp, errors.New(msg)) require.Equal(t, string(c.fasthttp.Response.Body()), msg) @@ -324,7 +324,7 @@ func Test_App_serverErrorHandler_Internal_Error(t *testing.T) { func Test_App_serverErrorHandler_Network_Error(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed app.serverErrorHandler(c.fasthttp, &net.DNSError{ Err: "test error", @@ -1400,8 +1400,7 @@ func Test_App_Next_Method(t *testing.T) { func Benchmark_AcquireCtx(b *testing.B) { app := New() for n := 0; n < b.N; n++ { - c := app.AcquireCtx() - c.Reset(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) app.ReleaseCtx(c) } @@ -1765,7 +1764,7 @@ func Test_App_SetTLSHandler(t *testing.T) { app := New() app.SetTLSHandler(tlsHandler) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) require.Equal(t, "example.golang", c.ClientHelloInfo().ServerName) diff --git a/bind_test.go b/bind_test.go index d8b3efe65a..f20255bc53 100644 --- a/bind_test.go +++ b/bind_test.go @@ -23,7 +23,7 @@ const helloWorld = "hello world" func Test_Bind_Query(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Query struct { ID int @@ -98,7 +98,7 @@ func Test_Bind_Query_Map(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -156,7 +156,7 @@ func Test_Bind_Query_WithSetParserDecoder(t *testing.T) { }) app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type NonRFCTimeInput struct { Date NonRFCTime `query:"date"` @@ -188,7 +188,7 @@ func Test_Bind_Query_WithSetParserDecoder(t *testing.T) { func Test_Bind_Query_Schema(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Query1 struct { Name string `query:"name,required"` @@ -289,7 +289,7 @@ func Test_Bind_Query_Schema(t *testing.T) { func Test_Bind_Header(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Header struct { ID int @@ -362,7 +362,7 @@ func Test_Bind_Header_Map(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -410,7 +410,7 @@ func Test_Bind_Header_WithSetParserDecoder(t *testing.T) { }) app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type NonRFCTimeInput struct { Date NonRFCTime `req:"date"` @@ -445,7 +445,7 @@ func Test_Bind_Header_WithSetParserDecoder(t *testing.T) { func Test_Bind_Header_Schema(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Header1 struct { Name string `header:"Name,required"` @@ -530,7 +530,7 @@ func Test_Bind_Header_Schema(t *testing.T) { func Test_Bind_RespHeader(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Header struct { ID int @@ -603,7 +603,7 @@ func Test_Bind_RespHeader_Map(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -632,7 +632,7 @@ func Benchmark_Bind_Query(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Query struct { ID int @@ -656,7 +656,7 @@ func Benchmark_Bind_Query_Map(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -675,7 +675,7 @@ func Benchmark_Bind_Query_WithParseParam(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Person struct { Name string `query:"name"` @@ -705,7 +705,7 @@ func Benchmark_Bind_Query_Comma(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Query struct { ID int @@ -730,7 +730,7 @@ func Benchmark_Bind_Header(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type ReqHeader struct { ID int @@ -757,7 +757,7 @@ func Benchmark_Bind_Header(b *testing.B) { func Benchmark_Bind_Header_Map(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -780,7 +780,7 @@ func Benchmark_Bind_RespHeader(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type ReqHeader struct { ID int @@ -807,7 +807,7 @@ func Benchmark_Bind_RespHeader(b *testing.B) { func Benchmark_Bind_RespHeader_Map(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -829,7 +829,7 @@ func Benchmark_Bind_RespHeader_Map(b *testing.B) { func Test_Bind_Body(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Demo struct { Name string `json:"name" xml:"name" form:"name" query:"name"` @@ -926,7 +926,7 @@ func Test_Bind_Body_WithSetParserDecoder(t *testing.T) { }) app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Demo struct { Date CustomTime `form:"date"` @@ -958,7 +958,7 @@ func Benchmark_Bind_Body_JSON(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Demo struct { Name string `json:"name"` @@ -984,7 +984,7 @@ func Benchmark_Bind_Body_XML(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Demo struct { Name string `xml:"name"` @@ -1010,7 +1010,7 @@ func Benchmark_Bind_Body_Form(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Demo struct { Name string `form:"name"` @@ -1036,7 +1036,7 @@ func Benchmark_Bind_Body_MultipartForm(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Demo struct { Name string `form:"name"` @@ -1063,7 +1063,7 @@ func Benchmark_Bind_Body_Form_Map(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) body := []byte("name=john") c.Request().SetBody(body) @@ -1131,7 +1131,7 @@ func Benchmark_Bind_URI(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.route = &Route{ Params: []string{ @@ -1168,7 +1168,7 @@ func Benchmark_Bind_URI_Map(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.route = &Route{ Params: []string{ @@ -1200,7 +1200,7 @@ func Test_Bind_Cookie(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Cookie struct { ID int @@ -1273,7 +1273,7 @@ func Test_Bind_Cookie_Map(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -1321,7 +1321,7 @@ func Test_Bind_Cookie_WithSetParserDecoder(t *testing.T) { }) app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type NonRFCTimeInput struct { Date NonRFCTime `cerez:"date"` @@ -1357,7 +1357,7 @@ func Test_Bind_Cookie_Schema(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Cookie1 struct { Name string `cookie:"Name,required"` @@ -1443,7 +1443,7 @@ func Benchmark_Bind_Cookie(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Cookie struct { ID int @@ -1472,7 +1472,7 @@ func Benchmark_Bind_Cookie_Map(b *testing.B) { var err error app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -1509,7 +1509,7 @@ func (*customBinder) Parse(c Ctx, out any) error { // go test -run Test_Bind_CustomBinder func Test_Bind_CustomBinder(t *testing.T) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // Register binder customBinder := &customBinder{} @@ -1533,7 +1533,7 @@ func Test_Bind_CustomBinder(t *testing.T) { // go test -run Test_Bind_Must func Test_Bind_Must(t *testing.T) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type RequiredQuery struct { Name string `query:"name,required"` @@ -1573,7 +1573,7 @@ type simpleQuery struct { // go test -run Test_Bind_StructValidator func Test_Bind_StructValidator(t *testing.T) { app := New(Config{StructValidator: &structValidator{}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) rq := new(simpleQuery) c.Request().URI().SetQueryString("name=efe") @@ -1588,7 +1588,7 @@ func Test_Bind_StructValidator(t *testing.T) { func Test_Bind_RepeatParserWithSameStruct(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) type Request struct { diff --git a/ctx_interface.go b/ctx_interface.go index 3eef6a6938..a608604a53 100644 --- a/ctx_interface.go +++ b/ctx_interface.go @@ -427,7 +427,7 @@ func NewDefaultCtx(app *App) *DefaultCtx { } } -func (app *App) NewCtx(fctx *fasthttp.RequestCtx) Ctx { +func (app *App) newCtx() Ctx { var c Ctx if app.newCtxFunc != nil { @@ -436,18 +436,18 @@ func (app *App) NewCtx(fctx *fasthttp.RequestCtx) Ctx { c = NewDefaultCtx(app) } - // Set request - c.setReq(fctx) - return c } // AcquireCtx retrieves a new Ctx from the pool. -func (app *App) AcquireCtx() Ctx { +func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) Ctx { ctx, ok := app.pool.Get().(Ctx) + if !ok { panic(errors.New("failed to type-assert to Ctx")) } + ctx.Reset(fctx) + return ctx } @@ -470,7 +470,7 @@ func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx) { c.pathOriginal = c.app.getString(fctx.URI().PathOriginal()) // Attach *fasthttp.RequestCtx to ctx - c.fasthttp = fctx + c.setReq(fctx) // reset base uri c.baseURI = "" diff --git a/ctx_test.go b/ctx_test.go index 48c893efb4..bef906ea3c 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -40,7 +40,7 @@ const epsilon = 0.001 func Test_Ctx_Accepts(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAccept, "text/html,application/xhtml+xml,application/xml;q=0.9") require.Equal(t, "", c.Accepts("")) @@ -70,7 +70,7 @@ func Test_Ctx_Accepts(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Accepts -benchmem -count=4 func Benchmark_Ctx_Accepts(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) acceptHeader := "text/html,application/xhtml+xml,application/xml;q=0.9" c.Request().Header.Set("Accept", acceptHeader) @@ -129,7 +129,7 @@ func Test_Ctx_CustomCtx(t *testing.T) { func Test_Ctx_Accepts_EmptyAccept(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, ".forwarded", c.Accepts(".forwarded")) } @@ -138,7 +138,7 @@ func Test_Ctx_Accepts_EmptyAccept(t *testing.T) { func Test_Ctx_Accepts_Wildcard(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAccept, "*/*;q=0.9") require.Equal(t, "html", c.Accepts("html")) @@ -152,7 +152,7 @@ func Test_Ctx_Accepts_Wildcard(t *testing.T) { func Test_Ctx_AcceptsCharsets(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAcceptCharset, "utf-8, iso-8859-1;q=0.5") require.Equal(t, "utf-8", c.AcceptsCharsets("utf-8")) @@ -161,7 +161,7 @@ func Test_Ctx_AcceptsCharsets(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_AcceptsCharsets -benchmem -count=4 func Benchmark_Ctx_AcceptsCharsets(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set("Accept-Charset", "utf-8, iso-8859-1;q=0.5") var res string @@ -177,7 +177,7 @@ func Benchmark_Ctx_AcceptsCharsets(b *testing.B) { func Test_Ctx_AcceptsEncodings(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAcceptEncoding, "deflate, gzip;q=1.0, *;q=0.5") require.Equal(t, "gzip", c.AcceptsEncodings("gzip")) @@ -187,7 +187,7 @@ func Test_Ctx_AcceptsEncodings(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_AcceptsEncodings -benchmem -count=4 func Benchmark_Ctx_AcceptsEncodings(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderAcceptEncoding, "deflate, gzip;q=1.0, *;q=0.5") var res string @@ -203,7 +203,7 @@ func Benchmark_Ctx_AcceptsEncodings(b *testing.B) { func Test_Ctx_AcceptsLanguages(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAcceptLanguage, "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5") require.Equal(t, "fr", c.AcceptsLanguages("fr")) @@ -212,7 +212,7 @@ func Test_Ctx_AcceptsLanguages(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_AcceptsLanguages -benchmem -count=4 func Benchmark_Ctx_AcceptsLanguages(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderAcceptLanguage, "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5") var res string @@ -229,7 +229,7 @@ func Test_Ctx_App(t *testing.T) { t.Parallel() app := New() app.config.BodyLimit = 1000 - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, 1000, c.App().config.BodyLimit) } @@ -238,7 +238,7 @@ func Test_Ctx_App(t *testing.T) { func Test_Ctx_Append(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Append("X-Test", "Hello") c.Append("X-Test", "World") @@ -273,7 +273,7 @@ func Test_Ctx_Append(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Append -benchmem -count=4 func Benchmark_Ctx_Append(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -289,7 +289,7 @@ func Benchmark_Ctx_Append(b *testing.B) { func Test_Ctx_Attachment(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // empty c.Attachment() @@ -306,7 +306,7 @@ func Test_Ctx_Attachment(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Attachment -benchmem -count=4 func Benchmark_Ctx_Attachment(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -321,7 +321,7 @@ func Benchmark_Ctx_Attachment(b *testing.B) { func Test_Ctx_BaseURL(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") require.Equal(t, "http://google.com", c.BaseURL()) @@ -332,7 +332,7 @@ func Test_Ctx_BaseURL(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_BaseURL -benchmem func Benchmark_Ctx_BaseURL(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().SetHost("google.com:1337") c.Request().URI().SetPath("/haha/oke/lol") @@ -349,7 +349,7 @@ func Benchmark_Ctx_BaseURL(b *testing.B) { func Test_Ctx_Body(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().SetBody([]byte("john=doe")) require.Equal(t, []byte("john=doe"), c.Body()) @@ -360,7 +360,7 @@ func Benchmark_Ctx_Body(b *testing.B) { const input = "john=doe" app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().SetBody([]byte(input)) b.ReportAllocs() @@ -377,7 +377,7 @@ func Test_Ctx_Body_Immutable(t *testing.T) { t.Parallel() app := New() app.config.Immutable = true - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().SetBody([]byte("john=doe")) require.Equal(t, []byte("john=doe"), c.Body()) @@ -389,7 +389,7 @@ func Benchmark_Ctx_Body_Immutable(b *testing.B) { app := New() app.config.Immutable = true - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().SetBody([]byte(input)) b.ReportAllocs() @@ -442,7 +442,7 @@ func Test_Ctx_Body_With_Compression(t *testing.T) { t.Run(tCase.name, func(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set("Content-Encoding", tCase.contentEncoding) if strings.Contains(tCase.contentEncoding, "gzip") { @@ -578,7 +578,7 @@ func Benchmark_Ctx_Body_With_Compression(b *testing.B) { b.Run(ct.contentEncoding, func(b *testing.B) { app := New() const input = "john=doe" - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Content-Encoding", ct.contentEncoding) compressedBody, err := ct.compressWriter([]byte(input)) @@ -635,7 +635,7 @@ func Test_Ctx_Body_With_Compression_Immutable(t *testing.T) { t.Parallel() app := New() app.config.Immutable = true - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set("Content-Encoding", tCase.contentEncoding) if strings.Contains(tCase.contentEncoding, "gzip") { @@ -772,7 +772,7 @@ func Benchmark_Ctx_Body_With_Compression_Immutable(b *testing.B) { app := New() app.config.Immutable = true const input = "john=doe" - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Content-Encoding", ct.contentEncoding) compressedBody, err := ct.compressWriter([]byte(input)) @@ -792,7 +792,7 @@ func Benchmark_Ctx_Body_With_Compression_Immutable(b *testing.B) { func Test_Ctx_Context(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, "*fasthttp.RequestCtx", fmt.Sprintf("%T", c.Context())) } @@ -801,7 +801,7 @@ func Test_Ctx_Context(t *testing.T) { func Test_Ctx_UserContext(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) t.Run("Nil_Context", func(t *testing.T) { t.Parallel() @@ -821,7 +821,7 @@ func Test_Ctx_UserContext(t *testing.T) { func Test_Ctx_SetUserContext(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) testKey := struct{}{} testValue := "Test Value" @@ -872,7 +872,7 @@ func Test_Ctx_UserContext_Multiple_Requests(t *testing.T) { func Test_Ctx_Cookie(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) expire := time.Now().Add(24 * time.Hour) var dst []byte @@ -924,7 +924,7 @@ func Test_Ctx_Cookie(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Cookie -benchmem -count=4 func Benchmark_Ctx_Cookie(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -941,7 +941,7 @@ func Benchmark_Ctx_Cookie(b *testing.B) { func Test_Ctx_Cookies(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Cookie", "john=doe") require.Equal(t, "doe", c.Cookies("john")) @@ -952,7 +952,7 @@ func Test_Ctx_Cookies(t *testing.T) { func Test_Ctx_Format(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // set `accepted` to whatever media type was chosen by Format var accepted string @@ -1001,7 +1001,7 @@ func Test_Ctx_Format(t *testing.T) { func Benchmark_Ctx_Format(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAccept, "application/json,text/plain; format=flowed; q=0.9") fail := func(_ Ctx) error { @@ -1068,7 +1068,7 @@ func Benchmark_Ctx_Format(b *testing.B) { func Test_Ctx_AutoFormat(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAccept, MIMETextPlain) err := c.AutoFormat([]byte("Hello, World!")) @@ -1114,7 +1114,7 @@ func Test_Ctx_AutoFormat(t *testing.T) { func Test_Ctx_AutoFormat_Struct(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type Message struct { Recipients []string @@ -1147,7 +1147,7 @@ func Test_Ctx_AutoFormat_Struct(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_AutoFormat -benchmem -count=4 func Benchmark_Ctx_AutoFormat(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Accept", "text/plain") b.ReportAllocs() @@ -1164,7 +1164,7 @@ func Benchmark_Ctx_AutoFormat(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_Ctx_AutoFormat_HTML -benchmem -count=4 func Benchmark_Ctx_AutoFormat_HTML(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Accept", "text/html") b.ReportAllocs() @@ -1181,7 +1181,7 @@ func Benchmark_Ctx_AutoFormat_HTML(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_Ctx_AutoFormat_JSON -benchmem -count=4 func Benchmark_Ctx_AutoFormat_JSON(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Accept", "application/json") b.ReportAllocs() @@ -1198,7 +1198,7 @@ func Benchmark_Ctx_AutoFormat_JSON(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_Ctx_AutoFormat_XML -benchmem -count=4 func Benchmark_Ctx_AutoFormat_XML(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("Accept", "application/xml") b.ReportAllocs() @@ -1282,7 +1282,7 @@ func Test_Ctx_FormValue(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Fresh_StaleEtag -benchmem -count=4 func Benchmark_Ctx_Fresh_StaleEtag(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) for n := 0; n < b.N; n++ { c.Request().Header.Set(HeaderIfNoneMatch, "a, b, c, d") @@ -1299,7 +1299,7 @@ func Benchmark_Ctx_Fresh_StaleEtag(b *testing.B) { func Test_Ctx_Fresh(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.False(t, c.Fresh()) @@ -1344,7 +1344,7 @@ func Test_Ctx_Fresh(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Fresh_WithNoCache -benchmem -count=4 func Benchmark_Ctx_Fresh_WithNoCache(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderIfNoneMatch, "*") c.Request().Header.Set(HeaderCacheControl, "no-cache") @@ -1369,7 +1369,7 @@ func Test_Ctx_Parsers(t *testing.T) { withValues := func(t *testing.T, actionFn func(c Ctx, testStruct *TestStruct) error) { t.Helper() - c := app.AcquireCtx() + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) testStruct := new(TestStruct) @@ -1453,7 +1453,7 @@ func Test_Ctx_Parsers(t *testing.T) { func Test_Ctx_Get(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderAcceptCharset, "utf-8, iso-8859-1;q=0.5") c.Request().Header.Set(HeaderReferer, "Monster") @@ -1466,7 +1466,7 @@ func Test_Ctx_Get(t *testing.T) { func Test_Ctx_Host(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") require.Equal(t, "google.com", c.Host()) @@ -1478,7 +1478,7 @@ func Test_Ctx_Host_UntrustedProxy(t *testing.T) { // Don't trust any proxy { app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google.com", c.Host()) @@ -1487,7 +1487,7 @@ func Test_Ctx_Host_UntrustedProxy(t *testing.T) { // Trust to specific proxy list { app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.8.0.0", "0.8.0.1"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google.com", c.Host()) @@ -1500,7 +1500,7 @@ func Test_Ctx_Host_TrustedProxy(t *testing.T) { t.Parallel() { app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0", "0.8.0.1"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google1.com", c.Host()) @@ -1513,7 +1513,7 @@ func Test_Ctx_Host_TrustedProxyRange(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0/30"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google1.com", c.Host()) @@ -1525,7 +1525,7 @@ func Test_Ctx_Host_UntrustedProxyRange(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"1.0.0.0/30"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google.com", c.Host()) @@ -1535,7 +1535,7 @@ func Test_Ctx_Host_UntrustedProxyRange(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Host -benchmem -count=4 func Benchmark_Ctx_Host(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") var host string b.ReportAllocs() @@ -1552,7 +1552,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) require.True(t, c.IsProxyTrusted()) } @@ -1560,7 +1560,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { app := New(Config{ EnableTrustedProxyCheck: false, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.True(t, c.IsProxyTrusted()) } @@ -1568,7 +1568,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { app := New(Config{ EnableTrustedProxyCheck: true, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.False(t, c.IsProxyTrusted()) } { @@ -1577,7 +1577,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { TrustedProxies: []string{}, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.False(t, c.IsProxyTrusted()) } { @@ -1588,7 +1588,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { "127.0.0.1", }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.False(t, c.IsProxyTrusted()) } { @@ -1599,7 +1599,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { "127.0.0.1/8", }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.False(t, c.IsProxyTrusted()) } { @@ -1610,7 +1610,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { "0.0.0.0", }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.True(t, c.IsProxyTrusted()) } { @@ -1621,7 +1621,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { "0.0.0.1/31", }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.True(t, c.IsProxyTrusted()) } { @@ -1632,7 +1632,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { "0.0.0.1/31junk", }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.False(t, c.IsProxyTrusted()) } } @@ -1641,7 +1641,7 @@ func Test_Ctx_IsProxyTrusted(t *testing.T) { func Test_Ctx_Hostname(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") require.Equal(t, "google.com", c.Hostname()) @@ -1653,7 +1653,7 @@ func Test_Ctx_Hostname(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Hostname -benchmem -count=4 func Benchmark_Ctx_Hostname(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com:8080/test") var hostname string b.ReportAllocs() @@ -1664,7 +1664,7 @@ func Benchmark_Ctx_Hostname(b *testing.B) { // Trust to specific proxy list { app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.8.0.0", "0.8.0.1"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(b, "google.com", hostname) @@ -1677,7 +1677,7 @@ func Test_Ctx_Hostname_TrustedProxy(t *testing.T) { t.Parallel() { app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0", "0.8.0.1"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google1.com", c.Hostname()) @@ -1690,7 +1690,7 @@ func Test_Ctx_Hostname_TrustedProxy_Multiple(t *testing.T) { t.Parallel() { app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0", "0.8.0.1"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com, google2.com") require.Equal(t, "google1.com", c.Hostname()) @@ -1703,7 +1703,7 @@ func Test_Ctx_Hostname_TrustedProxyRange(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0/30"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google1.com", c.Hostname()) @@ -1715,7 +1715,7 @@ func Test_Ctx_Hostname_UntrustedProxyRange(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"1.0.0.0/30"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://google.com/test") c.Request().Header.Set(HeaderXForwardedHost, "google1.com") require.Equal(t, "google.com", c.Hostname()) @@ -1726,7 +1726,7 @@ func Test_Ctx_Hostname_UntrustedProxyRange(t *testing.T) { func Test_Ctx_Port(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, "0", c.Port()) } @@ -1754,7 +1754,7 @@ func Test_Ctx_IP(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // default behavior will return the remote IP from the stack require.Equal(t, "0.0.0.0", c.IP()) @@ -1773,7 +1773,7 @@ func Test_Ctx_IP_ProxyHeader(t *testing.T) { for _, proxyHeaderName := range proxyHeaderNames { app := New(Config{ProxyHeader: proxyHeaderName}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(proxyHeaderName, "0.0.0.1") require.Equal(t, "0.0.0.1", c.IP()) @@ -1805,7 +1805,7 @@ func Test_Ctx_IP_ProxyHeader_With_IP_Validation(t *testing.T) { for _, proxyHeaderName := range proxyHeaderNames { app := New(Config{EnableIPValidation: true, ProxyHeader: proxyHeaderName}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // when proxy header & validation is enabled and the value is a valid IP, we return it c.Request().Header.Set(proxyHeaderName, "0.0.0.1") @@ -1833,7 +1833,7 @@ func Test_Ctx_IP_ProxyHeader_With_IP_Validation(t *testing.T) { func Test_Ctx_IP_UntrustedProxy(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.8.0.1"}, ProxyHeader: HeaderXForwardedFor}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "0.0.0.1") require.Equal(t, "0.0.0.0", c.IP()) } @@ -1842,7 +1842,7 @@ func Test_Ctx_IP_UntrustedProxy(t *testing.T) { func Test_Ctx_IP_TrustedProxy(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0"}, ProxyHeader: HeaderXForwardedFor}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "0.0.0.1") require.Equal(t, "0.0.0.1", c.IP()) } @@ -1851,7 +1851,7 @@ func Test_Ctx_IP_TrustedProxy(t *testing.T) { func Test_Ctx_IPs(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // normal happy path test case c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1, 127.0.0.2, 127.0.0.3") @@ -1887,7 +1887,7 @@ func Test_Ctx_IPs(t *testing.T) { func Test_Ctx_IPs_With_IP_Validation(t *testing.T) { t.Parallel() app := New(Config{EnableIPValidation: true}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // normal happy path test case c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1, 127.0.0.2, 127.0.0.3") @@ -1923,7 +1923,7 @@ func Test_Ctx_IPs_With_IP_Validation(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_IPs -benchmem -count=4 func Benchmark_Ctx_IPs(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1, invalid, 127.0.0.1") var res []string b.ReportAllocs() @@ -1936,7 +1936,7 @@ func Benchmark_Ctx_IPs(b *testing.B) { func Benchmark_Ctx_IPs_v6(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) c.Request().Header.Set(HeaderXForwardedFor, "f037:825e:eadb:1b7b:1667:6f0a:5356:f604, invalid, 2345:0425:2CA1::0567:5673:23b5") var res []string @@ -1950,7 +1950,7 @@ func Benchmark_Ctx_IPs_v6(b *testing.B) { func Benchmark_Ctx_IPs_With_IP_Validation(b *testing.B) { app := New(Config{EnableIPValidation: true}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1, invalid, 127.0.0.1") var res []string b.ReportAllocs() @@ -1963,7 +1963,7 @@ func Benchmark_Ctx_IPs_With_IP_Validation(b *testing.B) { func Benchmark_Ctx_IPs_v6_With_IP_Validation(b *testing.B) { app := New(Config{EnableIPValidation: true}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) c.Request().Header.Set(HeaderXForwardedFor, "2345:0425:2CA1:0000:0000:0567:5673:23b5, invalid, 2345:0425:2CA1::0567:5673:23b5") var res []string @@ -1977,7 +1977,7 @@ func Benchmark_Ctx_IPs_v6_With_IP_Validation(b *testing.B) { func Benchmark_Ctx_IP_With_ProxyHeader(b *testing.B) { app := New(Config{ProxyHeader: HeaderXForwardedFor}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1") var res string b.ReportAllocs() @@ -1990,7 +1990,7 @@ func Benchmark_Ctx_IP_With_ProxyHeader(b *testing.B) { func Benchmark_Ctx_IP_With_ProxyHeader_and_IP_Validation(b *testing.B) { app := New(Config{ProxyHeader: HeaderXForwardedFor, EnableIPValidation: true}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1") var res string b.ReportAllocs() @@ -2003,7 +2003,7 @@ func Benchmark_Ctx_IP_With_ProxyHeader_and_IP_Validation(b *testing.B) { func Benchmark_Ctx_IP(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request() var res string b.ReportAllocs() @@ -2018,7 +2018,7 @@ func Benchmark_Ctx_IP(b *testing.B) { func Test_Ctx_Is(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderContentType, MIMETextHTML+"; boundary=something") require.True(t, c.Is(".html")) @@ -2052,7 +2052,7 @@ func Test_Ctx_Is(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Is -benchmem -count=4 func Benchmark_Ctx_Is(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderContentType, MIMEApplicationJSON) var res bool @@ -2133,7 +2133,7 @@ func Test_Ctx_Method(t *testing.T) { fctx := &fasthttp.RequestCtx{} fctx.Request.Header.SetMethod(MethodGet) app := New() - c := app.NewCtx(fctx) + c := app.AcquireCtx(fctx) require.Equal(t, MethodGet, c.Method()) c.Method(MethodPost) @@ -2289,7 +2289,7 @@ func Benchmark_Ctx_MultipartForm(b *testing.B) { func Test_Ctx_OriginalURL(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.SetRequestURI("http://google.com/test?search=demo") require.Equal(t, "http://google.com/test?search=demo", c.OriginalURL()) @@ -2368,7 +2368,7 @@ func Test_Ctx_Params_Case_Sensitive(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Params -benchmem -count=4 func Benchmark_Ctx_Params(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.route = &Route{ Params: []string{ @@ -2419,7 +2419,7 @@ func Test_Ctx_Protocol(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, "HTTP/1.1", c.Protocol()) @@ -2431,7 +2431,7 @@ func Test_Ctx_Protocol(t *testing.T) { func Benchmark_Ctx_Protocol(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) var res string b.ReportAllocs() @@ -2450,7 +2450,7 @@ func Test_Ctx_Scheme(t *testing.T) { freq := &fasthttp.RequestCtx{} freq.Request.Header.Set("X-Forwarded", "invalid") - c := app.NewCtx(freq) + c := app.AcquireCtx(freq) c.Request().Header.Set(HeaderXForwardedProto, schemeHTTPS) require.Equal(t, schemeHTTPS, c.Scheme()) @@ -2482,7 +2482,7 @@ func Test_Ctx_Scheme(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Scheme -benchmem -count=4 func Benchmark_Ctx_Scheme(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) var res string b.ReportAllocs() @@ -2497,7 +2497,7 @@ func Benchmark_Ctx_Scheme(b *testing.B) { func Test_Ctx_Scheme_TrustedProxy(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedProto, schemeHTTPS) require.Equal(t, schemeHTTPS, c.Scheme()) @@ -2522,7 +2522,7 @@ func Test_Ctx_Scheme_TrustedProxy(t *testing.T) { func Test_Ctx_Scheme_TrustedProxyRange(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.0.0.0/30"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedProto, schemeHTTPS) require.Equal(t, schemeHTTPS, c.Scheme()) @@ -2547,7 +2547,7 @@ func Test_Ctx_Scheme_TrustedProxyRange(t *testing.T) { func Test_Ctx_Scheme_UntrustedProxyRange(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"1.1.1.1/30"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedProto, schemeHTTPS) require.Equal(t, schemeHTTP, c.Scheme()) @@ -2572,7 +2572,7 @@ func Test_Ctx_Scheme_UntrustedProxyRange(t *testing.T) { func Test_Ctx_Scheme_UnTrustedProxy(t *testing.T) { t.Parallel() app := New(Config{EnableTrustedProxyCheck: true, TrustedProxies: []string{"0.8.0.1"}}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedProto, schemeHTTPS) require.Equal(t, schemeHTTP, c.Scheme()) @@ -2597,7 +2597,7 @@ func Test_Ctx_Scheme_UnTrustedProxy(t *testing.T) { func Test_Ctx_Query(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=20") require.Equal(t, "john", c.Query("search")) @@ -2613,7 +2613,7 @@ func Test_Ctx_Query(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Query -benchmem -count=4 func Benchmark_Ctx_Query(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res string b.ReportAllocs() @@ -2628,7 +2628,7 @@ func Benchmark_Ctx_Query(b *testing.B) { func Test_Ctx_QuerySignedInt(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") // int @@ -2675,7 +2675,7 @@ func Test_Ctx_QuerySignedInt(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QuerySignedInt -benchmem -count=4 func Benchmark_Ctx_QuerySignedInt(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res int b.ReportAllocs() @@ -2690,7 +2690,7 @@ func Benchmark_Ctx_QuerySignedInt(b *testing.B) { func Test_Ctx_QueryBoundarySignedInt(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) var q string // int @@ -2735,7 +2735,7 @@ func Test_Ctx_QueryBoundarySignedInt(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryBoundarySignedInt -benchmem -count=4 func Benchmark_Ctx_QueryBoundarySignedInt(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res int b.ReportAllocs() @@ -2750,7 +2750,7 @@ func Benchmark_Ctx_QueryBoundarySignedInt(b *testing.B) { func Test_Ctx_QueryUnsignedInt(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") // uint @@ -2797,7 +2797,7 @@ func Test_Ctx_QueryUnsignedInt(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryUnsignedInt -benchmem -count=4 func Benchmark_Ctx_QueryUnsignedInt(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res uint b.ReportAllocs() @@ -2812,7 +2812,7 @@ func Benchmark_Ctx_QueryUnsignedInt(b *testing.B) { func Test_Ctx_QueryBoundaryUnsignedInt(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) var q string // uint @@ -2857,7 +2857,7 @@ func Test_Ctx_QueryBoundaryUnsignedInt(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryBoundaryUnsignedInt -benchmem -count=4 func Benchmark_Ctx_QueryBoundaryUnsignedInt(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res uint b.ReportAllocs() @@ -2872,7 +2872,7 @@ func Benchmark_Ctx_QueryBoundaryUnsignedInt(b *testing.B) { func Test_Ctx_QueryFloat(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("name=alex&amount=32.23&id=") @@ -2896,7 +2896,7 @@ func Test_Ctx_QueryFloat(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryFloat -benchmem -count=4 func Benchmark_Ctx_QueryFloat(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res float32 b.ReportAllocs() @@ -2911,7 +2911,7 @@ func Benchmark_Ctx_QueryFloat(b *testing.B) { func Test_Ctx_QueryBool(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("name=alex&want_pizza=false&id=") @@ -2926,7 +2926,7 @@ func Test_Ctx_QueryBool(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryBool -benchmem -count=4 func Benchmark_Ctx_QueryBool(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res bool b.ReportAllocs() @@ -2941,7 +2941,7 @@ func Benchmark_Ctx_QueryBool(b *testing.B) { func Test_Ctx_QueryString(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("name=alex&amount=32.23&id=") @@ -2956,7 +2956,7 @@ func Test_Ctx_QueryString(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryString -benchmem -count=4 func Benchmark_Ctx_QueryString(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res string b.ReportAllocs() @@ -2971,7 +2971,7 @@ func Benchmark_Ctx_QueryString(b *testing.B) { func Test_Ctx_QueryBytes(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("name=alex&amount=32.23&id=") @@ -2986,7 +2986,7 @@ func Test_Ctx_QueryBytes(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryBytes -benchmem -count=4 func Benchmark_Ctx_QueryBytes(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res []byte b.ReportAllocs() @@ -3001,7 +3001,7 @@ func Benchmark_Ctx_QueryBytes(b *testing.B) { func Test_Ctx_QueryWithoutGenericDataType(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("name=alex&amount=32.23&isAgent=true&id=32") @@ -3040,7 +3040,7 @@ func Test_Ctx_QueryWithoutGenericDataType(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_QueryWithoutGenericDataType -benchmem -count=4 func Benchmark_Ctx_QueryWithoutGenericDataType(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetQueryString("search=john&age=8") var res int b.ReportAllocs() @@ -3055,7 +3055,7 @@ func Benchmark_Ctx_QueryWithoutGenericDataType(b *testing.B) { func Test_Ctx_Range(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) testRange := func(header string, ranges ...RangeSet) { c.Request().Header.Set(HeaderRange, header) @@ -3088,7 +3088,7 @@ func Test_Ctx_Range(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Range -benchmem -count=4 func Benchmark_Ctx_Range(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) testCases := []struct { @@ -3132,7 +3132,7 @@ func Test_Ctx_Route(t *testing.T) { require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, "/", c.Route().Path) require.Equal(t, MethodGet, c.Route().Method) @@ -3245,7 +3245,7 @@ func Test_Ctx_SaveFileToStorage(t *testing.T) { func Test_Ctx_Secure(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // TODO Add TLS conn require.False(t, c.Secure()) @@ -3255,7 +3255,7 @@ func Test_Ctx_Secure(t *testing.T) { func Test_Ctx_Stale(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.True(t, c.Stale()) } @@ -3264,7 +3264,7 @@ func Test_Ctx_Stale(t *testing.T) { func Test_Ctx_Subdomains(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().URI().SetHost("john.doe.is.awesome.google.com") require.Equal(t, []string{"john", "doe"}, c.Subdomains(4)) @@ -3276,7 +3276,7 @@ func Test_Ctx_Subdomains(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Subdomains -benchmem -count=4 func Benchmark_Ctx_Subdomains(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetRequestURI("http://john.doe.google.com") var res []string @@ -3292,7 +3292,7 @@ func Benchmark_Ctx_Subdomains(b *testing.B) { func Test_Ctx_ClearCookie(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderCookie, "john=doe") c.ClearCookie("john") @@ -3309,7 +3309,7 @@ func Test_Ctx_ClearCookie(t *testing.T) { func Test_Ctx_Download(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.NoError(t, c.Download("ctx.go", "Awesome File!")) @@ -3346,7 +3346,7 @@ func Test_Ctx_SendFile(t *testing.T) { require.NoError(t, err) // simple test case - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err = c.SendFile("ctx.go") // check expectation require.NoError(t, err) @@ -3355,7 +3355,7 @@ func Test_Ctx_SendFile(t *testing.T) { app.ReleaseCtx(c) // test with custom error code - c = app.NewCtx(&fasthttp.RequestCtx{}) + c = app.AcquireCtx(&fasthttp.RequestCtx{}) err = c.Status(StatusInternalServerError).SendFile("ctx.go") // check expectation require.NoError(t, err) @@ -3364,7 +3364,7 @@ func Test_Ctx_SendFile(t *testing.T) { app.ReleaseCtx(c) // test not modified - c = app.NewCtx(&fasthttp.RequestCtx{}) + c = app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderIfModifiedSince, fI.ModTime().Format(time.RFC1123)) err = c.SendFile("ctx.go") // check expectation @@ -3458,7 +3458,7 @@ func Test_Ctx_SendFile_RestoreOriginalURL(t *testing.T) { func Test_Ctx_JSON(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Error(t, c.JSON(complex(1, 1))) @@ -3499,7 +3499,7 @@ func Test_Ctx_JSON(t *testing.T) { return []byte(`["custom","json"]`), nil }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.JSON(Map{ // map has no order "Name": "Grame", @@ -3514,7 +3514,7 @@ func Test_Ctx_JSON(t *testing.T) { // go test -run=^$ -bench=Benchmark_Ctx_JSON -benchmem -count=4 func Benchmark_Ctx_JSON(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type SomeStruct struct { Name string @@ -3538,7 +3538,7 @@ func Benchmark_Ctx_JSON(b *testing.B) { func Benchmark_Ctx_JSON_Ctype(b *testing.B) { app := New() // TODO: Check extra allocs because of the interface stuff - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed type SomeStruct struct { Name string Age uint8 @@ -3562,7 +3562,7 @@ func Benchmark_Ctx_JSON_Ctype(b *testing.B) { func Test_Ctx_JSONP(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Error(t, c.JSONP(complex(1, 1))) @@ -3590,7 +3590,7 @@ func Test_Ctx_JSONP(t *testing.T) { return []byte(`["custom","json"]`), nil }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.JSONP(Map{ // map has no order "Name": "Grame", @@ -3605,7 +3605,7 @@ func Test_Ctx_JSONP(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_JSONP -benchmem -count=4 func Benchmark_Ctx_JSONP(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed type SomeStruct struct { Name string @@ -3630,7 +3630,7 @@ func Benchmark_Ctx_JSONP(b *testing.B) { func Test_Ctx_XML(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed require.Error(t, c.JSON(complex(1, 1))) @@ -3667,7 +3667,7 @@ func Test_Ctx_XML(t *testing.T) { return []byte(`xml`), nil }, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) type xmlResult struct { XMLName xml.Name `xml:"Users"` @@ -3689,7 +3689,7 @@ func Test_Ctx_XML(t *testing.T) { // go test -run=^$ -bench=Benchmark_Ctx_XML -benchmem -count=4 func Benchmark_Ctx_XML(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed type SomeStruct struct { Name string `xml:"Name"` Age uint8 `xml:"Age"` @@ -3713,7 +3713,7 @@ func Benchmark_Ctx_XML(b *testing.B) { func Test_Ctx_Links(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Links() require.Equal(t, "", string(c.Response().Header.Peek(HeaderLink))) @@ -3728,7 +3728,7 @@ func Test_Ctx_Links(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Links -benchmem -count=4 func Benchmark_Ctx_Links(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -3744,7 +3744,7 @@ func Benchmark_Ctx_Links(b *testing.B) { func Test_Ctx_Location(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Location("http://example.com") require.Equal(t, "http://example.com", string(c.Response().Header.Peek(HeaderLocation))) @@ -3786,7 +3786,7 @@ func Test_Ctx_Next_Error(t *testing.T) { func Test_Ctx_Render(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Render("./.github/testdata/index.tmpl", Map{ "Title": "Hello, World!", @@ -3807,7 +3807,7 @@ func Test_Ctx_RenderWithoutLocals(t *testing.T) { app := New(Config{ PassLocalsToViews: false, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Locals("Title", "Hello, World!") @@ -3824,7 +3824,7 @@ func Test_Ctx_RenderWithLocals(t *testing.T) { t.Run("EmptyBind", func(t *testing.T) { t.Parallel() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Locals("Title", "Hello, World!") err := c.Render("./.github/testdata/index.tmpl", Map{}) @@ -3835,7 +3835,7 @@ func Test_Ctx_RenderWithLocals(t *testing.T) { t.Run("NilBind", func(t *testing.T) { t.Parallel() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Locals("Title", "Hello, World!") err := c.Render("./.github/testdata/index.tmpl", nil) @@ -3849,7 +3849,7 @@ func Test_Ctx_RenderWithBindVars(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.BindVars(Map{ "Title": "Hello, World!", @@ -3869,7 +3869,7 @@ func Test_Ctx_RenderWithBindVars(t *testing.T) { func Test_Ctx_RenderWithOverwrittenBind(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.BindVars(Map{ "Title": "Hello, World!", @@ -3894,7 +3894,7 @@ func Test_Ctx_RenderWithBindVarsLocals(t *testing.T) { PassLocalsToViews: true, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.BindVars(Map{ "Title": "Hello, World!", @@ -3920,7 +3920,7 @@ func Test_Ctx_RenderWithLocalsAndBinding(t *testing.T) { PassLocalsToViews: true, Views: engine, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Locals("Title", "This is a test.") @@ -3940,7 +3940,7 @@ func Benchmark_Ctx_RenderWithLocalsAndBindVars(b *testing.B) { PassLocalsToViews: true, Views: engine, }) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err = c.BindVars(Map{ "Title": "Hello, World!", @@ -3967,7 +3967,7 @@ func Benchmark_Ctx_RenderLocals(b *testing.B) { PassLocalsToViews: true, }) app.config.Views = engine - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Locals("Title", "Hello, World!") @@ -3988,7 +3988,7 @@ func Benchmark_Ctx_RenderBindVars(b *testing.B) { require.NoError(b, err) app := New() app.config.Views = engine - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err = c.BindVars(Map{ "Title": "Hello, World!", @@ -4107,7 +4107,7 @@ func Test_Ctx_Render_Engine(t *testing.T) { require.NoError(t, engine.Load()) app := New() app.config.Views = engine - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Render("index.tmpl", Map{ "Title": "Hello, World!", @@ -4123,7 +4123,7 @@ func Test_Ctx_Render_Engine_With_View_Layout(t *testing.T) { require.NoError(t, engine.Load()) app := New(Config{ViewsLayout: "main.tmpl"}) app.config.Views = engine - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Render("index.tmpl", Map{ "Title": "Hello, World!", @@ -4139,7 +4139,7 @@ func Benchmark_Ctx_Render_Engine(b *testing.B) { require.NoError(b, err) app := New() app.config.Views = engine - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) b.ReportAllocs() b.ResetTimer() @@ -4155,7 +4155,7 @@ func Benchmark_Ctx_Render_Engine(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_Ctx_Get_Location_From_Route -benchmem -count=4 func Benchmark_Ctx_Get_Location_From_Route(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed app.Get("/user/:name", func(c Ctx) error { return c.SendString(c.Params("name")) @@ -4178,7 +4178,7 @@ func Test_Ctx_Get_Location_From_Route_name(t *testing.T) { t.Run("case insensitive", func(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) app.Get("/user/:name", func(c Ctx) error { return c.SendString(c.Params("name")) }).Name("User") @@ -4195,7 +4195,7 @@ func Test_Ctx_Get_Location_From_Route_name(t *testing.T) { t.Run("case sensitive", func(t *testing.T) { t.Parallel() app := New(Config{CaseSensitive: true}) - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) app.Get("/user/:name", func(c Ctx) error { return c.SendString(c.Params("name")) @@ -4215,7 +4215,7 @@ func Test_Ctx_Get_Location_From_Route_name(t *testing.T) { func Test_Ctx_Get_Location_From_Route_name_Optional_greedy(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) app.Get("/:phone/*/send/*", func(c Ctx) error { return c.SendString("Phone: " + c.Params("phone") + "\nFirst Param: " + c.Params("*1") + "\nSecond Param: " + c.Params("*2")) @@ -4234,7 +4234,7 @@ func Test_Ctx_Get_Location_From_Route_name_Optional_greedy(t *testing.T) { func Test_Ctx_Get_Location_From_Route_name_Optional_greedy_one_param(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) app.Get("/:phone/*/send", func(c Ctx) error { return c.SendString("Phone: " + c.Params("phone") + "\nFirst Param: " + c.Params("*1")) @@ -4261,7 +4261,7 @@ func Test_Ctx_Render_Engine_Error(t *testing.T) { t.Parallel() app := New() app.config.Views = errorTemplateEngine{} - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Render("index.tmpl", nil) require.Error(t, err) @@ -4285,7 +4285,7 @@ func Test_Ctx_Render_Go_Template(t *testing.T) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err = c.Render(file.Name(), nil) require.NoError(t, err) @@ -4296,7 +4296,7 @@ func Test_Ctx_Render_Go_Template(t *testing.T) { func Test_Ctx_Send(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.NoError(t, c.Send([]byte("Hello, World"))) require.NoError(t, c.Send([]byte("Don't crash please"))) @@ -4307,7 +4307,7 @@ func Test_Ctx_Send(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Send -benchmem -count=4 func Benchmark_Ctx_Send(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) byt := []byte("Hello, World!") b.ReportAllocs() @@ -4325,7 +4325,7 @@ func Benchmark_Ctx_Send(b *testing.B) { func Test_Ctx_SendStatus(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.SendStatus(415) require.NoError(t, err) @@ -4337,7 +4337,7 @@ func Test_Ctx_SendStatus(t *testing.T) { func Test_Ctx_SendString(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.SendString("Don't crash please") require.NoError(t, err) @@ -4348,7 +4348,7 @@ func Test_Ctx_SendString(t *testing.T) { func Test_Ctx_SendStream(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.SendStream(bytes.NewReader([]byte("Don't crash please"))) require.NoError(t, err) @@ -4367,7 +4367,7 @@ func Test_Ctx_SendStream(t *testing.T) { func Test_Ctx_Set(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Set("X-1", "1") c.Set("X-2", "2") @@ -4382,7 +4382,7 @@ func Test_Ctx_Set(t *testing.T) { func Test_Ctx_Set_Splitter(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Set("Location", "foo\r\nSet-Cookie:%20SESSIONID=MaliciousValue\r\n") h := string(c.Response().Header.Peek("Location")) @@ -4396,7 +4396,7 @@ func Test_Ctx_Set_Splitter(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Set -benchmem -count=4 func Benchmark_Ctx_Set(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) val := "1431-15132-3423" b.ReportAllocs() @@ -4410,7 +4410,7 @@ func Benchmark_Ctx_Set(b *testing.B) { func Test_Ctx_Status(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Status(400) require.Equal(t, 400, c.Response().StatusCode()) @@ -4424,7 +4424,7 @@ func Test_Ctx_Status(t *testing.T) { func Test_Ctx_Type(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Type(".json") require.Equal(t, "application/json", string(c.Response().Header.Peek("Content-Type"))) @@ -4442,7 +4442,7 @@ func Test_Ctx_Type(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Type -benchmem -count=4 func Benchmark_Ctx_Type(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) b.ReportAllocs() b.ResetTimer() @@ -4455,7 +4455,7 @@ func Benchmark_Ctx_Type(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_Ctx_Type_Charset -benchmem -count=4 func Benchmark_Ctx_Type_Charset(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -4469,7 +4469,7 @@ func Benchmark_Ctx_Type_Charset(b *testing.B) { func Test_Ctx_Vary(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Vary("Origin") c.Vary("User-Agent") @@ -4480,7 +4480,7 @@ func Test_Ctx_Vary(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Vary -benchmem -count=4 func Benchmark_Ctx_Vary(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -4493,7 +4493,7 @@ func Benchmark_Ctx_Vary(b *testing.B) { func Test_Ctx_Write(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) _, err := c.Write([]byte("Hello, ")) require.NoError(t, err) @@ -4505,7 +4505,7 @@ func Test_Ctx_Write(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Write -benchmem -count=4 func Benchmark_Ctx_Write(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) byt := []byte("Hello, World!") b.ReportAllocs() @@ -4522,7 +4522,7 @@ func Benchmark_Ctx_Write(b *testing.B) { func Test_Ctx_Writef(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) world := "World!" _, err := c.Writef("Hello, %s", world) @@ -4533,7 +4533,7 @@ func Test_Ctx_Writef(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Writef -benchmem -count=4 func Benchmark_Ctx_Writef(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed world := "World!" b.ReportAllocs() @@ -4550,7 +4550,7 @@ func Benchmark_Ctx_Writef(b *testing.B) { func Test_Ctx_WriteString(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) _, err := c.WriteString("Hello, ") require.NoError(t, err) @@ -4563,7 +4563,7 @@ func Test_Ctx_WriteString(t *testing.T) { func Test_Ctx_XHR(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXRequestedWith, "XMLHttpRequest") require.True(t, c.XHR()) @@ -4572,7 +4572,7 @@ func Test_Ctx_XHR(t *testing.T) { // go test -run=^$ -bench=Benchmark_Ctx_XHR -benchmem -count=4 func Benchmark_Ctx_XHR(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXRequestedWith, "XMLHttpRequest") var equal bool @@ -4587,7 +4587,7 @@ func Benchmark_Ctx_XHR(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_Ctx_SendString_B -benchmem -count=4 func Benchmark_Ctx_SendString_B(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) body := "Hello, world!" b.ReportAllocs() @@ -4605,7 +4605,7 @@ func Benchmark_Ctx_SendString_B(b *testing.B) { func Test_Ctx_Queries(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().SetBody([]byte(``)) c.Request().Header.SetContentType("") @@ -4653,7 +4653,7 @@ func Test_Ctx_Queries(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Ctx_Queries -benchmem -count=4 func Benchmark_Ctx_Queries(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) b.ReportAllocs() b.ResetTimer() @@ -4722,7 +4722,7 @@ func Benchmark_Ctx_BodyStreamWriter(b *testing.B) { func Test_Ctx_String(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) require.Equal(t, "#0000000000000000 - 0.0.0.0:0 <-> 0.0.0.0:0 - GET http:///", c.String()) } @@ -4731,7 +4731,7 @@ func Test_Ctx_String(t *testing.T) { func Benchmark_Ctx_String(b *testing.B) { var str string app := New() - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) b.ReportAllocs() b.ResetTimer() @@ -4832,7 +4832,7 @@ func Test_Ctx_IsFromLocal_X_Forwarded(t *testing.T) { // Test unset X-Forwarded-For header. { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) // fasthttp returns "0.0.0.0" as IP as there is no remote address. require.Equal(t, "0.0.0.0", c.IP()) require.False(t, c.IsFromLocal()) @@ -4840,7 +4840,7 @@ func Test_Ctx_IsFromLocal_X_Forwarded(t *testing.T) { // Test when setting X-Forwarded-For header to localhost "127.0.0.1" { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "127.0.0.1") defer app.ReleaseCtx(c) require.False(t, c.IsFromLocal()) @@ -4848,7 +4848,7 @@ func Test_Ctx_IsFromLocal_X_Forwarded(t *testing.T) { // Test when setting X-Forwarded-For header to localhost "::1" { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "::1") defer app.ReleaseCtx(c) require.False(t, c.IsFromLocal()) @@ -4856,7 +4856,7 @@ func Test_Ctx_IsFromLocal_X_Forwarded(t *testing.T) { // Test when setting X-Forwarded-For to full localhost IPv6 address "0:0:0:0:0:0:0:1" { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "0:0:0:0:0:0:0:1") defer app.ReleaseCtx(c) require.False(t, c.IsFromLocal()) @@ -4864,7 +4864,7 @@ func Test_Ctx_IsFromLocal_X_Forwarded(t *testing.T) { // Test for a random IP address. { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderXForwardedFor, "93.46.8.90") require.False(t, c.IsFromLocal()) @@ -4889,7 +4889,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { app := New() fastCtx := &fasthttp.RequestCtx{} fastCtx.SetRemoteAddr(localIPv4) - c := app.NewCtx(fastCtx) + c := app.AcquireCtx(fastCtx) require.Equal(t, "127.0.0.1", c.IP()) require.True(t, c.IsFromLocal()) @@ -4899,7 +4899,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { app := New() fastCtx := &fasthttp.RequestCtx{} fastCtx.SetRemoteAddr(localIPv6) - c := app.NewCtx(fastCtx) + c := app.AcquireCtx(fastCtx) require.Equal(t, "::1", c.IP()) require.True(t, c.IsFromLocal()) } @@ -4908,7 +4908,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { app := New() fastCtx := &fasthttp.RequestCtx{} fastCtx.SetRemoteAddr(localIPv6long) - c := app.NewCtx(fastCtx) + c := app.AcquireCtx(fastCtx) // fasthttp should return "::1" for "0:0:0:0:0:0:0:1". // otherwise IsFromLocal() will break. require.Equal(t, "::1", c.IP()) @@ -4919,7 +4919,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { app := New() fastCtx := &fasthttp.RequestCtx{} fastCtx.SetRemoteAddr(zeroIPv4) - c := app.NewCtx(fastCtx) + c := app.AcquireCtx(fastCtx) require.Equal(t, "0.0.0.0", c.IP()) require.False(t, c.IsFromLocal()) } @@ -4928,7 +4928,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { app := New() fastCtx := &fasthttp.RequestCtx{} fastCtx.SetRemoteAddr(someIPv4) - c := app.NewCtx(fastCtx) + c := app.AcquireCtx(fastCtx) require.Equal(t, "93.46.8.90", c.IP()) require.False(t, c.IsFromLocal()) } @@ -4937,7 +4937,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { app := New() fastCtx := &fasthttp.RequestCtx{} fastCtx.SetRemoteAddr(someIPv6) - c := app.NewCtx(fastCtx) + c := app.AcquireCtx(fastCtx) require.Equal(t, "2001:db8:85a3::8a2e:370:7334", c.IP()) require.False(t, c.IsFromLocal()) } @@ -4946,7 +4946,7 @@ func Test_Ctx_IsFromLocal_RemoteAddr(t *testing.T) { // go test -run Test_Ctx_extractIPsFromHeader -v func Test_Ctx_extractIPsFromHeader(t *testing.T) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("x-forwarded-for", "1.1.1.1,8.8.8.8 , /n, \n,1.1, a.c, 6.,6., , a,,42.118.81.169,10.0.137.108") ips := c.IPs() res := ips[len(ips)-2] @@ -4957,7 +4957,7 @@ func Test_Ctx_extractIPsFromHeader(t *testing.T) { func Test_Ctx_extractIPsFromHeader_EnableValidateIp(t *testing.T) { app := New() app.config.EnableIPValidation = true - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("x-forwarded-for", "1.1.1.1,8.8.8.8 , /n, \n,1.1, a.c, 6.,6., , a,,42.118.81.169,10.0.137.108") ips := c.IPs() res := ips[len(ips)-2] @@ -4968,7 +4968,7 @@ func Test_Ctx_extractIPsFromHeader_EnableValidateIp(t *testing.T) { func Test_Ctx_GetRespHeaders(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Set("test", "Hello, World 👋!") c.Set("foo", "bar") @@ -4986,7 +4986,7 @@ func Test_Ctx_GetRespHeaders(t *testing.T) { func Benchmark_Ctx_GetRespHeaders(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Response().Header.Set("test", "Hello, World 👋!") c.Response().Header.Set("foo", "bar") @@ -5011,7 +5011,7 @@ func Benchmark_Ctx_GetRespHeaders(b *testing.B) { func Test_Ctx_GetReqHeaders(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("test", "Hello, World 👋!") c.Request().Header.Set("foo", "bar") @@ -5029,7 +5029,7 @@ func Test_Ctx_GetReqHeaders(t *testing.T) { func Benchmark_Ctx_GetReqHeaders(b *testing.B) { app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set("test", "Hello, World 👋!") c.Request().Header.Set("foo", "bar") diff --git a/go.mod b/go.mod index 8411e1d122..2471590fc0 100644 --- a/go.mod +++ b/go.mod @@ -18,10 +18,8 @@ require ( github.com/andybalholm/brotli v1.1.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/klauspost/compress v1.17.6 // indirect - github.com/mattn/go-runewidth v0.0.15 // indirect github.com/philhofer/fwd v1.1.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - github.com/rivo/uniseg v0.2.0 // indirect github.com/valyala/tcplisten v1.0.0 // indirect golang.org/x/sys v0.17.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 82eafabc24..bf4bb8a486 100644 --- a/go.sum +++ b/go.sum @@ -15,14 +15,10 @@ github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovk github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= -github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U= -github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= 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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= -github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/tinylib/msgp v1.1.8 h1:FCXC1xanKO4I8plpHGH2P7koL/RzZs12l/+r7vakfm0= diff --git a/middleware/adaptor/adaptor.go b/middleware/adaptor/adaptor.go index bb06218e22..82059cf158 100644 --- a/middleware/adaptor/adaptor.go +++ b/middleware/adaptor/adaptor.go @@ -160,7 +160,7 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc { fctx.Init(req, remoteAddr, nil) if len(h) > 0 { // New fiber Ctx - ctx := app.NewCtx(&fctx) + ctx := app.AcquireCtx(&fctx) // Execute fiber Ctx err := h[0](ctx) if err != nil { diff --git a/middleware/adaptor/adaptor_test.go b/middleware/adaptor/adaptor_test.go index 7a6fa95cea..2982fb4042 100644 --- a/middleware/adaptor/adaptor_test.go +++ b/middleware/adaptor/adaptor_test.go @@ -87,7 +87,7 @@ func Test_HTTPHandler(t *testing.T) { fctx.Init(&req, remoteAddr, nil) app := fiber.New() - ctx := app.NewCtx(&fctx) + ctx := app.AcquireCtx(&fctx) defer app.ReleaseCtx(ctx) err = fiberH(ctx) diff --git a/middleware/csrf/csrf_test.go b/middleware/csrf/csrf_test.go index 83504bb2f8..99cbf85e48 100644 --- a/middleware/csrf/csrf_test.go +++ b/middleware/csrf/csrf_test.go @@ -79,16 +79,16 @@ func Test_CSRF_WithSession(t *testing.T) { // fiber context ctx := &fasthttp.RequestCtx{} - defer app.ReleaseCtx(app.NewCtx(ctx)) + defer app.ReleaseCtx(app.AcquireCtx(ctx)) // get session - sess, err := store.Get(app.NewCtx(ctx)) + sess, err := store.Get(app.AcquireCtx(ctx)) require.NoError(t, err) require.True(t, sess.Fresh()) // the session string is no longer be 123 newSessionIDString := sess.ID() - app.NewCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString) + app.AcquireCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString) // middleware config config := Config{ @@ -212,16 +212,16 @@ func Test_CSRF_ExpiredToken_WithSession(t *testing.T) { // fiber context ctx := &fasthttp.RequestCtx{} - defer app.ReleaseCtx(app.NewCtx(ctx)) + defer app.ReleaseCtx(app.AcquireCtx(ctx)) // get session - sess, err := store.Get(app.NewCtx(ctx)) + sess, err := store.Get(app.AcquireCtx(ctx)) require.NoError(t, err) require.True(t, sess.Fresh()) // get session id newSessionIDString := sess.ID() - app.NewCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString) + app.AcquireCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString) // middleware config config := Config{ @@ -714,9 +714,9 @@ func Test_CSRF_DeleteToken(t *testing.T) { ctx.Request.Header.SetMethod(fiber.MethodPost) ctx.Request.Header.Set(HeaderName, token) ctx.Request.Header.SetCookie(ConfigDefault.CookieName, token) - handler := HandlerFromContext(app.NewCtx(ctx)) + handler := HandlerFromContext(app.AcquireCtx(ctx)) if handler != nil { - if err := handler.DeleteToken(app.NewCtx(ctx)); err != nil { + if err := handler.DeleteToken(app.AcquireCtx(ctx)); err != nil { t.Fatal(err) } } @@ -746,13 +746,13 @@ func Test_CSRF_DeleteToken_WithSession(t *testing.T) { ctx := &fasthttp.RequestCtx{} // get session - sess, err := store.Get(app.NewCtx(ctx)) + sess, err := store.Get(app.AcquireCtx(ctx)) require.NoError(t, err) require.True(t, sess.Fresh()) // the session string is no longer be 123 newSessionIDString := sess.ID() - app.NewCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString) + app.AcquireCtx(ctx).Request().Header.SetCookie("_session", newSessionIDString) // middleware config config := Config{ @@ -781,9 +781,9 @@ func Test_CSRF_DeleteToken_WithSession(t *testing.T) { ctx.Request.Header.SetMethod(fiber.MethodPost) ctx.Request.Header.Set(HeaderName, token) ctx.Request.Header.SetCookie(ConfigDefault.CookieName, token) - handler := HandlerFromContext(app.NewCtx(ctx)) + handler := HandlerFromContext(app.AcquireCtx(ctx)) if handler != nil { - if err := handler.DeleteToken(app.NewCtx(ctx)); err != nil { + if err := handler.DeleteToken(app.AcquireCtx(ctx)); err != nil { t.Fatal(err) } } diff --git a/middleware/session/session_test.go b/middleware/session/session_test.go index 94ddd8b798..f9166cabe4 100644 --- a/middleware/session/session_test.go +++ b/middleware/session/session_test.go @@ -21,7 +21,7 @@ func Test_Session(t *testing.T) { app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // set session ctx.Request().Header.SetCookie(store.sessionName, "123") @@ -69,7 +69,7 @@ func Test_Session(t *testing.T) { require.NoError(t, err) // requesting entirely new context to prevent falsy tests - ctx = app.NewCtx(&fasthttp.RequestCtx{}) + ctx = app.AcquireCtx(&fasthttp.RequestCtx{}) sess, err = store.Get(ctx) require.NoError(t, err) @@ -80,7 +80,7 @@ func Test_Session(t *testing.T) { // when we use the original session for the second time // the session be should be same if the session is not expired - ctx = app.NewCtx(&fasthttp.RequestCtx{}) + ctx = app.AcquireCtx(&fasthttp.RequestCtx{}) // request the server with the old session ctx.Request().Header.SetCookie(store.sessionName, id) @@ -101,7 +101,7 @@ func Test_Session_Types(t *testing.T) { app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // set cookie ctx.Request().Header.SetCookie(store.sessionName, "123") @@ -265,7 +265,7 @@ func Test_Session_Store_Reset(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -298,7 +298,7 @@ func Test_Session_Save(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -320,7 +320,7 @@ func Test_Session_Save(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -347,7 +347,7 @@ func Test_Session_Save_Expiration(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -389,7 +389,7 @@ func Test_Session_Destroy(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -410,7 +410,7 @@ func Test_Session_Destroy(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -449,7 +449,7 @@ func Test_Session_Cookie(t *testing.T) { // fiber instance app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -467,7 +467,7 @@ func Test_Session_Cookie_In_Response(t *testing.T) { app := fiber.New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // get session sess, err := store.Get(ctx) @@ -492,7 +492,7 @@ func Test_Session_Deletes_Single_Key(t *testing.T) { store := New() app := fiber.New() - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) sess, err := store.Get(ctx) require.NoError(t, err) @@ -522,7 +522,7 @@ func Test_Session_Reset(t *testing.T) { store := New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) t.Run("reset session data and id, and set fresh to be true", func(t *testing.T) { t.Parallel() @@ -590,7 +590,7 @@ func Test_Session_Regenerate(t *testing.T) { // a random session uuid originalSessionUUIDString := "" // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // now the session is in the storage freshSession, err := store.Get(ctx) @@ -622,7 +622,7 @@ func Test_Session_Regenerate(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Session -benchmem -count=4 func Benchmark_Session(b *testing.B) { app, store := fiber.New(), New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) c.Request().Header.SetCookie(store.sessionName, "12356789") diff --git a/middleware/session/store_test.go b/middleware/session/store_test.go index bd7160fa2d..130f13feba 100644 --- a/middleware/session/store_test.go +++ b/middleware/session/store_test.go @@ -22,7 +22,7 @@ func TestStore_getSessionID(t *testing.T) { // session store store := New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // set cookie ctx.Request().Header.SetCookie(store.sessionName, expectedID) @@ -37,7 +37,7 @@ func TestStore_getSessionID(t *testing.T) { KeyLookup: "header:session_id", }) // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // set header ctx.Request().Header.Set(store.sessionName, expectedID) @@ -52,7 +52,7 @@ func TestStore_getSessionID(t *testing.T) { KeyLookup: "query:session_id", }) // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // set url parameter ctx.Request().SetRequestURI(fmt.Sprintf("/path?%s=%s", store.sessionName, expectedID)) @@ -73,7 +73,7 @@ func TestStore_Get(t *testing.T) { // session store store := New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // set cookie ctx.Request().Header.SetCookie(store.sessionName, unexpectedID) @@ -94,7 +94,7 @@ func TestStore_DeleteSession(t *testing.T) { store := New() // fiber context - ctx := app.NewCtx(&fasthttp.RequestCtx{}) + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) // Create a new session session, err := store.Get(ctx) diff --git a/redirect_test.go b/redirect_test.go index 65f437f190..d49f526771 100644 --- a/redirect_test.go +++ b/redirect_test.go @@ -21,7 +21,7 @@ import ( func Test_Redirect_To(t *testing.T) { t.Parallel() app := New() - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().To("http://default.com") require.NoError(t, err) @@ -41,7 +41,7 @@ func Test_Redirect_Route_WithParams(t *testing.T) { app.Get("/user/:name", func(c Ctx) error { return c.JSON(c.Params("name")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().Route("user", RedirectConfig{ Params: Map{ @@ -60,7 +60,7 @@ func Test_Redirect_Route_WithParams_WithQueries(t *testing.T) { app.Get("/user/:name", func(c Ctx) error { return c.JSON(c.Params("name")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().Route("user", RedirectConfig{ Params: Map{ @@ -84,7 +84,7 @@ func Test_Redirect_Route_WithOptionalParams(t *testing.T) { app.Get("/user/:name?", func(c Ctx) error { return c.JSON(c.Params("name")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().Route("user", RedirectConfig{ Params: Map{ @@ -103,7 +103,7 @@ func Test_Redirect_Route_WithOptionalParamsWithoutValue(t *testing.T) { app.Get("/user/:name?", func(c Ctx) error { return c.JSON(c.Params("name")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().Route("user") require.NoError(t, err) @@ -118,7 +118,7 @@ func Test_Redirect_Route_WithGreedyParameters(t *testing.T) { app.Get("/user/+", func(c Ctx) error { return c.JSON(c.Params("+")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().Route("user", RedirectConfig{ Params: Map{ @@ -137,7 +137,7 @@ func Test_Redirect_Back(t *testing.T) { app.Get("/", func(c Ctx) error { return c.JSON("Home") }).Name("home") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) err := c.Redirect().Back("/") require.NoError(t, err) @@ -159,7 +159,7 @@ func Test_Redirect_Back_WithReferer(t *testing.T) { app.Get("/back", func(c Ctx) error { return c.JSON("Back") }).Name("back") - c := app.NewCtx(&fasthttp.RequestCtx{}) + c := app.AcquireCtx(&fasthttp.RequestCtx{}) c.Request().Header.Set(HeaderReferer, "/back") err := c.Redirect().Back("/") @@ -178,7 +178,7 @@ func Test_Redirect_Route_WithFlashMessages(t *testing.T) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed err := c.Redirect().With("success", "1").With("message", "test").Route("user") require.NoError(t, err) @@ -201,7 +201,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().URI().SetQueryString("id=1&name=tom") err := c.Redirect().With("success", "1").With("message", "test").WithInput().Route("user") @@ -229,7 +229,7 @@ func Test_Redirect_setFlash(t *testing.T) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderCookie, "fiber_flash=success:1,message:test,old_input_data_name:tom,old_input_data_id:1") @@ -336,7 +336,7 @@ func Benchmark_Redirect_Route(b *testing.B) { return c.JSON(c.Params("name")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -363,7 +363,7 @@ func Benchmark_Redirect_Route_WithQueries(b *testing.B) { return c.JSON(c.Params("name")) }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -395,7 +395,7 @@ func Benchmark_Redirect_Route_WithFlashMessages(b *testing.B) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ReportAllocs() b.ResetTimer() @@ -424,7 +424,7 @@ func Benchmark_Redirect_setFlash(b *testing.B) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderCookie, "fiber_flash=success:1,message:test,old_input_data_name:tom,old_input_data_id:1") @@ -453,7 +453,7 @@ func Benchmark_Redirect_Messages(b *testing.B) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderCookie, "fiber_flash=success:1,message:test,old_input_data_name:tom,old_input_data_id:1") c.Redirect().setFlash() @@ -478,7 +478,7 @@ func Benchmark_Redirect_OldInputs(b *testing.B) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderCookie, "fiber_flash=success:1,message:test,old_input_data_name:tom,old_input_data_id:1") c.Redirect().setFlash() @@ -503,7 +503,7 @@ func Benchmark_Redirect_Message(b *testing.B) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderCookie, "fiber_flash=success:1,message:test,old_input_data_name:tom,old_input_data_id:1") c.Redirect().setFlash() @@ -528,7 +528,7 @@ func Benchmark_Redirect_OldInput(b *testing.B) { return c.SendString("user") }).Name("user") - c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed c.Request().Header.Set(HeaderCookie, "fiber_flash=success:1,message:test,old_input_data_name:tom,old_input_data_id:1") c.Redirect().setFlash() diff --git a/router.go b/router.go index 42d5a1760b..f77b240a66 100644 --- a/router.go +++ b/router.go @@ -208,12 +208,12 @@ func (app *App) requestHandler(rctx *fasthttp.RequestCtx) { var c CustomCtx var ok bool if app.newCtxFunc != nil { - c, ok = app.AcquireCtx().(CustomCtx) + c, ok = app.AcquireCtx(rctx).(CustomCtx) if !ok { panic(errors.New("failed to type-assert to CustomCtx")) } } else { - c, ok = app.AcquireCtx().(*DefaultCtx) + c, ok = app.AcquireCtx(rctx).(*DefaultCtx) if !ok { panic(errors.New("failed to type-assert to *DefaultCtx")) } diff --git a/router_test.go b/router_test.go index 743a58edac..c25a317e32 100644 --- a/router_test.go +++ b/router_test.go @@ -651,7 +651,7 @@ func Benchmark_Router_Next(b *testing.B) { var res bool var err error - c := app.NewCtx(request).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed + c := app.AcquireCtx(request).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed b.ResetTimer() for n := 0; n < b.N; n++ { @@ -832,8 +832,7 @@ func Benchmark_Router_Github_API(b *testing.B) { for n := 0; n < b.N; n++ { c.URI().SetPath(routesFixture.TestRoutes[i].Path) - ctx := app.AcquireCtx().(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed - ctx.Reset(c) + ctx := app.AcquireCtx(c).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed match, err = app.next(ctx) app.ReleaseCtx(ctx) From e623e1dbfc87478be0eb83f8768c1b5958849e2e Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Tue, 27 Feb 2024 09:31:17 -0500 Subject: [PATCH 42/51] Update middleware/cors/utils.go Co-authored-by: Renan Bastos --- middleware/cors/utils.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/middleware/cors/utils.go b/middleware/cors/utils.go index d1280899c9..a12ba85a49 100644 --- a/middleware/cors/utils.go +++ b/middleware/cors/utils.go @@ -81,5 +81,5 @@ func normalizeOrigin(origin string) (bool, string) { // Normalize the origin by constructing it from the scheme and host. // The path or trailing slash is not included in the normalized origin. - return true, strings.ToLower(parsedOrigin.Scheme) + "://" + strings.ToLower(parsedOrigin.Host) + return true, strings.ToLower(parsedOrigin.Scheme + "://" + parsedOrigin.Host) } From 420d51d2047e07ce5988e9dbd854a1af6fb98f11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 19:02:59 +0100 Subject: [PATCH 43/51] fix sync_docs.sh --- .github/scripts/sync_docs.sh | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/.github/scripts/sync_docs.sh b/.github/scripts/sync_docs.sh index 1bdb80a8b7..0c7c6c9167 100755 --- a/.github/scripts/sync_docs.sh +++ b/.github/scripts/sync_docs.sh @@ -18,15 +18,15 @@ git config --global user.name "${AUTHOR_USERNAME}" git clone https://${TOKEN}@${REPO_URL} fiber-docs # Handle push event -#if [ "$EVENT" == "push" ]; then -# latest_commit=$(git rev-parse --short HEAD) -# log_output=$(git log --oneline ${BRANCH} HEAD~1..HEAD --name-status -- docs/) -# if [[ $log_output != "" ]]; then -# cp -a docs/* fiber-docs/docs/${REPO_DIR} -# fi -# -## Handle release event -#el +if [ "$EVENT" == "push" ]; then + latest_commit=$(git rev-parse --short HEAD) + log_output=$(git log --oneline ${BRANCH} HEAD~1..HEAD --name-status -- docs/) + if [[ $log_output != "" ]]; then + cp -a docs/* fiber-docs/docs/${REPO_DIR} + fi + +# Handle release event +el if [ "$EVENT" == "release" ]; then major_version="${TAG_NAME%%.*}" From 639f5525b397f7a46d41ff1d60298ed25c29da5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 19:31:46 +0100 Subject: [PATCH 44/51] fix review comments/hints --- docs/api/middleware/encryptcookie.md | 4 +- go.mod | 1 - go.sum | 2 - log/default.go | 9 ++++ log/default_test.go | 78 ++++++++++++++++++++------- middleware/cors/cors.go | 5 +- middleware/healthcheck/healthcheck.go | 7 +-- 7 files changed, 76 insertions(+), 30 deletions(-) diff --git a/docs/api/middleware/encryptcookie.md b/docs/api/middleware/encryptcookie.md index f5c7a5a40c..c153b6412d 100644 --- a/docs/api/middleware/encryptcookie.md +++ b/docs/api/middleware/encryptcookie.md @@ -83,9 +83,9 @@ var ConfigDefault = Config{ ``` ## Usage With Other Middlewares That Reads Or Modify Cookies -Place the encryptcookie middleware before any other middleware that reads or modifies cookies. For example, if you are using the CSRF middleware, ensure that the encryptcookie middleware is placed before it. Failure to do so may prevent the CSRF middleware from reading the encrypted cookie. +Place the `encryptcookie` middleware before any other middleware that reads or modifies cookies. For example, if you are using the CSRF middleware, ensure that the `encryptcookie` middleware is placed before it. Failure to do so may prevent the CSRF middleware from reading the encrypted cookie. -You may also choose to exclude certain cookies from encryption. For instance, if you are using the CSRF middleware with a frontend framework like Angular, and the framework reads the token from a cookie, you should exclude that cookie from encryption. This can be achieved by adding the cookie name to the Except array in the configuration: +You may also choose to exclude certain cookies from encryption. For instance, if you are using the `CSRF` middleware with a frontend framework like Angular, and the framework reads the token from a cookie, you should exclude that cookie from encryption. This can be achieved by adding the cookie name to the Except array in the configuration: ```go app.Use(encryptcookie.New(encryptcookie.Config{ diff --git a/go.mod b/go.mod index 2471590fc0..18a074025e 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,6 @@ module github.com/gofiber/fiber/v3 go 1.20 require ( - github.com/gofiber/fiber/v2 v2.52.0 github.com/gofiber/utils/v2 v2.0.0-beta.3 github.com/google/uuid v1.6.0 github.com/mattn/go-colorable v0.1.13 diff --git a/go.sum b/go.sum index bf4bb8a486..e74a99a27b 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,6 @@ github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1 github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gofiber/fiber/v2 v2.52.0 h1:S+qXi7y+/Pgvqq4DrSmREGiFwtB7Bu6+QFLuIHYw/UE= -github.com/gofiber/fiber/v2 v2.52.0/go.mod h1:KEOE+cXMhXG0zHc9d8+E38hoX+ZN7bhOtgeF2oT6jrQ= github.com/gofiber/utils/v2 v2.0.0-beta.3 h1:pfOhUDDVjBJpkWv6C5jaDyYLvpui7zQ97zpyFFsUOKw= github.com/gofiber/utils/v2 v2.0.0-beta.3/go.mod h1:jsl17+MsKfwJjM3ONCE9Rzji/j8XNbwjhUVTjzgfDCo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= diff --git a/log/default.go b/log/default.go index a7a60abd23..e9c3d1bbbd 100644 --- a/log/default.go +++ b/log/default.go @@ -31,6 +31,9 @@ func (l *defaultLogger) privateLog(lv Level, fmtArgs []any) { buf.WriteString(fmt.Sprint(fmtArgs...)) _ = l.stdlog.Output(l.depth, buf.String()) //nolint:errcheck // It is fine to ignore the error + if lv == LevelPanic { + panic(buf.String()) + } buf.Reset() bytebufferpool.Put(buf) if lv == LevelFatal { @@ -54,6 +57,9 @@ func (l *defaultLogger) privateLogf(lv Level, format string, fmtArgs []any) { _, _ = fmt.Fprint(buf, fmtArgs...) } _ = l.stdlog.Output(l.depth, buf.String()) //nolint:errcheck // It is fine to ignore the error + if lv == LevelPanic { + panic(buf.String()) + } buf.Reset() bytebufferpool.Put(buf) if lv == LevelFatal { @@ -92,6 +98,9 @@ func (l *defaultLogger) privateLogw(lv Level, format string, keysAndValues []any } _ = l.stdlog.Output(l.depth, buf.String()) //nolint:errcheck // It is fine to ignore the error + if lv == LevelPanic { + panic(buf.String()) + } buf.Reset() bytebufferpool.Put(buf) if lv == LevelFatal { diff --git a/log/default_test.go b/log/default_test.go index 9e820b6f4a..ae106977ea 100644 --- a/log/default_test.go +++ b/log/default_test.go @@ -28,6 +28,22 @@ func (w *byteSliceWriter) Write(p []byte) (int, error) { return len(p), nil } +func Test_WithContextCaller(t *testing.T) { + logger = &defaultLogger{ + stdlog: log.New(os.Stderr, "", log.Lshortfile), + depth: 4, + } + + var w byteSliceWriter + SetOutput(&w) + ctx := context.TODO() + + WithContext(ctx).Info("") + Info("") + + require.Equal(t, "default_test.go:41: [Info] \ndefault_test.go:42: [Info] \n", string(w.b)) +} + func Test_DefaultLogger(t *testing.T) { initDefaultLogger() @@ -39,7 +55,21 @@ func Test_DefaultLogger(t *testing.T) { Info("starting work") Warn("work may fail") Error("work failed") - Panic("work panic") + + didPanic := false + func() { + defer func() { + if r := recover(); r != nil { + didPanic = true + } + }() + Panic("work panic") + }() + + if !didPanic { + t.Errorf("Expected a panic when the panic logger method is called") + } + require.Equal(t, "[Trace] trace work\n"+ "[Debug] received work order\n"+ "[Info] starting work\n"+ @@ -59,7 +89,20 @@ func Test_DefaultFormatLogger(t *testing.T) { Infof("starting %s", work) Warnf("%s may fail", work) Errorf("%s failed", work) - Panicf("%s panic", work) + + didPanic := false + func() { + defer func() { + if r := recover(); r != nil { + didPanic = true + } + }() + Panicf("%s panic", work) + }() + + if !didPanic { + t.Errorf("Expected a panic when the panic logger method is called") + } require.Equal(t, "[Trace] trace work\n"+ "[Debug] received work order\n"+ @@ -82,7 +125,20 @@ func Test_CtxLogger(t *testing.T) { WithContext(ctx).Infof("starting %s", work) WithContext(ctx).Warnf("%s may fail", work) WithContext(ctx).Errorf("%s failed %d", work, 50) - WithContext(ctx).Panicf("%s panic", work) + + didPanic := false + func() { + defer func() { + if r := recover(); r != nil { + didPanic = true + } + }() + WithContext(ctx).Panicf("%s panic", work) + }() + + if !didPanic { + t.Errorf("Expected a panic when the panic logger method is called") + } require.Equal(t, "[Trace] trace work\n"+ "[Debug] received work order\n"+ @@ -210,22 +266,6 @@ func BenchmarkLogfKeyAndValues(b *testing.B) { } } -func Test_WithContextCaller(t *testing.T) { - logger = &defaultLogger{ - stdlog: log.New(os.Stderr, "", log.Lshortfile), - depth: 4, - } - - var w byteSliceWriter - SetOutput(&w) - ctx := context.TODO() - - WithContext(ctx).Info("") - Info("") - - require.Equal(t, "default_test.go:223: [Info] \ndefault_test.go:224: [Info] \n", string(w.b)) -} - func Test_SetLevel(t *testing.T) { setLogger := &defaultLogger{ stdlog: log.New(os.Stderr, "", log.LstdFlags|log.Lshortfile|log.Lmicroseconds), diff --git a/middleware/cors/cors.go b/middleware/cors/cors.go index 3a9400d2ac..99f483550d 100644 --- a/middleware/cors/cors.go +++ b/middleware/cors/cors.go @@ -110,7 +110,7 @@ func New(config ...Config) fiber.Handler { // Validate CORS credentials configuration if cfg.AllowCredentials && cfg.AllowOrigins == "*" { - panic("[CORS] Insecure setup, 'AllowCredentials' is set to true, and 'AllowOrigins' is set to a wildcard.") + log.Panic("[CORS] Insecure setup, 'AllowCredentials' is set to true, and 'AllowOrigins' is set to a wildcard.") //nolint:revive // we want to exit the program } // Validate and normalize static AllowOrigins if not using AllowOriginsFunc @@ -121,8 +121,7 @@ func New(config ...Config) fiber.Handler { if isValid { validatedOrigins = append(validatedOrigins, normalizedOrigin) } else { - log.Warnf("[CORS] Invalid origin format in configuration: %s", origin) - panic("[CORS] Invalid origin provided in configuration") + log.Panicf("[CORS] Invalid origin format in configuration: %s", origin) //nolint:revive // we want to exit the program } } cfg.AllowOrigins = strings.Join(validatedOrigins, ",") diff --git a/middleware/healthcheck/healthcheck.go b/middleware/healthcheck/healthcheck.go index f4eeb75423..222b6f4452 100644 --- a/middleware/healthcheck/healthcheck.go +++ b/middleware/healthcheck/healthcheck.go @@ -1,7 +1,8 @@ package healthcheck import ( - "github.com/gofiber/fiber/v2/utils" + "strings" + "github.com/gofiber/fiber/v3" ) @@ -41,12 +42,12 @@ func New(config ...Config) fiber.Handler { return c.Next() } - prefixCount := len(utils.TrimRight(c.Route().Path, '/')) + prefixCount := len(strings.TrimRight(c.Route().Path, "/")) if len(c.Path()) >= prefixCount { checkPath := c.Path()[prefixCount:] checkPathTrimmed := checkPath if !c.App().Config().StrictRouting { - checkPathTrimmed = utils.TrimRight(checkPath, '/') + checkPathTrimmed = strings.TrimRight(checkPath, "/") } switch { case checkPath == cfg.ReadinessEndpoint || checkPathTrimmed == cfg.ReadinessEndpoint: From 4c9e76dace9cf15977d2ee584515d36e11c9134c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 20:26:43 +0100 Subject: [PATCH 45/51] fix review comments/hints --- .github/scripts/sync_docs.sh | 3 +-- middleware/cors/cors.go | 2 +- middleware/healthcheck/healthcheck_test.go | 3 +++ middleware/session/session_test.go | 19 ++++++++++++++++--- router.go | 4 ++-- 5 files changed, 23 insertions(+), 8 deletions(-) diff --git a/.github/scripts/sync_docs.sh b/.github/scripts/sync_docs.sh index 0c7c6c9167..4898039680 100755 --- a/.github/scripts/sync_docs.sh +++ b/.github/scripts/sync_docs.sh @@ -26,8 +26,7 @@ if [ "$EVENT" == "push" ]; then fi # Handle release event -el -if [ "$EVENT" == "release" ]; then +elif [ "$EVENT" == "release" ]; then major_version="${TAG_NAME%%.*}" # Form new version name diff --git a/middleware/cors/cors.go b/middleware/cors/cors.go index 99f483550d..de96c1a689 100644 --- a/middleware/cors/cors.go +++ b/middleware/cors/cors.go @@ -197,7 +197,7 @@ func New(config ...Config) fiber.Handler { c.Set(fiber.HeaderAccessControlAllowOrigin, allowOrigin) c.Set(fiber.HeaderAccessControlAllowCredentials, "true") } else if allowOrigin == "*" { - log.Warn("[CORS] 'AllowCredentials' is true, but 'AllowOrigins' cannot be set to '*'.") + log.Warn("[CORS] 'AllowCredentials' is true. Ensure 'AllowOrigins' is not set to '*' in the configuration.") } } else { // For non-credential requests, it's safe to set to '*' or specific origins diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index d3ec7bedac..409b985a60 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -56,6 +56,7 @@ func Test_HealthCheck_Group_Default(t *testing.T) { v3Group := app.Group("/v3/") v3Group.Group("/todos/", New(Config{ReadinessEndpoint: "/readyz/", LivenessEndpoint: "/livez/"})) + // Testing health check endpoints in versioned API groups shouldGiveOK(t, app, "/v1/readyz") shouldGiveOK(t, app, "/v1/livez") shouldGiveOK(t, app, "/v1/readyz/") @@ -139,6 +140,7 @@ func Test_HealthCheck_Custom(t *testing.T) { ReadinessEndpoint: "/ready", })) + // Setup custom liveness and readiness probes to simulate application health status // Live should return 200 with GET request shouldGiveOK(t, app, "/live") // Live should return 404 with POST request @@ -182,6 +184,7 @@ func Test_HealthCheck_Custom_Nested(t *testing.T) { ReadinessEndpoint: "/probe/ready", })) + // Testing custom health check endpoints with nested paths shouldGiveOK(t, app, "/probe/live") shouldGiveStatus(t, app, "/probe/ready", fiber.StatusServiceUnavailable) shouldGiveOK(t, app, "/probe/live/") diff --git a/middleware/session/session_test.go b/middleware/session/session_test.go index f9166cabe4..ab2741b95e 100644 --- a/middleware/session/session_test.go +++ b/middleware/session/session_test.go @@ -22,6 +22,7 @@ func Test_Session(t *testing.T) { // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // set session ctx.Request().Header.SetCookie(store.sessionName, "123") @@ -80,7 +81,9 @@ func Test_Session(t *testing.T) { // when we use the original session for the second time // the session be should be same if the session is not expired + app.ReleaseCtx(ctx) ctx = app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // request the server with the old session ctx.Request().Header.SetCookie(store.sessionName, id) @@ -102,6 +105,7 @@ func Test_Session_Types(t *testing.T) { // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // set cookie ctx.Request().Header.SetCookie(store.sessionName, "123") @@ -266,6 +270,7 @@ func Test_Session_Store_Reset(t *testing.T) { app := fiber.New() // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -321,6 +326,7 @@ func Test_Session_Save(t *testing.T) { app := fiber.New() // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -348,6 +354,7 @@ func Test_Session_Save_Expiration(t *testing.T) { app := fiber.New() // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -390,6 +397,7 @@ func Test_Session_Destroy(t *testing.T) { app := fiber.New() // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -411,6 +419,7 @@ func Test_Session_Destroy(t *testing.T) { app := fiber.New() // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -450,6 +459,7 @@ func Test_Session_Cookie(t *testing.T) { app := fiber.New() // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -468,6 +478,7 @@ func Test_Session_Cookie_In_Response(t *testing.T) { // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // get session sess, err := store.Get(ctx) @@ -493,6 +504,7 @@ func Test_Session_Deletes_Single_Key(t *testing.T) { app := fiber.New() ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) sess, err := store.Get(ctx) require.NoError(t, err) @@ -521,11 +533,11 @@ func Test_Session_Reset(t *testing.T) { // session store store := New() - // fiber context - ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) - t.Run("reset session data and id, and set fresh to be true", func(t *testing.T) { t.Parallel() + // fiber context + ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // a random session uuid originalSessionUUIDString := "" @@ -591,6 +603,7 @@ func Test_Session_Regenerate(t *testing.T) { originalSessionUUIDString := "" // fiber context ctx := app.AcquireCtx(&fasthttp.RequestCtx{}) + defer app.ReleaseCtx(ctx) // now the session is in the storage freshSession, err := store.Get(ctx) diff --git a/router.go b/router.go index f77b240a66..4347c7ba9f 100644 --- a/router.go +++ b/router.go @@ -210,12 +210,12 @@ func (app *App) requestHandler(rctx *fasthttp.RequestCtx) { if app.newCtxFunc != nil { c, ok = app.AcquireCtx(rctx).(CustomCtx) if !ok { - panic(errors.New("failed to type-assert to CustomCtx")) + panic(errors.New("requestHandler: failed to type-assert to CustomCtx")) } } else { c, ok = app.AcquireCtx(rctx).(*DefaultCtx) if !ok { - panic(errors.New("failed to type-assert to *DefaultCtx")) + panic(errors.New("requestHandler: failed to type-assert to *DefaultCtx")) } } c.Reset(rctx) From e392d04b615e0b6185d442616beef2caee4c55a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 20:41:26 +0100 Subject: [PATCH 46/51] stabilize Test_Proxy_Timeout_Slow_Server test --- middleware/proxy/proxy_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/middleware/proxy/proxy_test.go b/middleware/proxy/proxy_test.go index 86ea58efe6..1d245b1a9f 100644 --- a/middleware/proxy/proxy_test.go +++ b/middleware/proxy/proxy_test.go @@ -299,17 +299,17 @@ func Test_Proxy_Timeout_Slow_Server(t *testing.T) { t.Parallel() _, addr := createProxyTestServer(t, func(c fiber.Ctx) error { - time.Sleep(2 * time.Second) + time.Sleep(300 * time.Millisecond) return c.SendString("fiber is awesome") }) app := fiber.New() app.Use(Balancer(Config{ Servers: []string{addr}, - Timeout: 3 * time.Second, + Timeout: 600 * time.Millisecond, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 5000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) From 4bd6090bd37df834b9ac8bff780da0f4bc965f45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 20:57:19 +0100 Subject: [PATCH 47/51] stabilize Test_Proxy_.* tests --- middleware/proxy/proxy_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/middleware/proxy/proxy_test.go b/middleware/proxy/proxy_test.go index 1d245b1a9f..408ee71a5f 100644 --- a/middleware/proxy/proxy_test.go +++ b/middleware/proxy/proxy_test.go @@ -492,7 +492,7 @@ func Test_Proxy_DoTimeout_Timeout(t *testing.T) { return DoTimeout(c, "http://"+addr, time.Second) }) - _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) + _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int((1*time.Second)/time.Millisecond)) require.Equal(t, errors.New("test: timeout error 1000ms"), err1) } @@ -532,7 +532,7 @@ func Test_Proxy_DoDeadline_PastDeadline(t *testing.T) { return DoDeadline(c, "http://"+addr, time.Now().Add(time.Second)) }) - _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) + _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int((1*time.Second)/time.Millisecond)) require.Equal(t, errors.New("test: timeout error 1000ms"), err1) } From 4a1891b4b94824ee0f0975cddb39475d77d4a97d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Tue, 27 Feb 2024 21:17:31 +0100 Subject: [PATCH 48/51] ignore bodyclose linter for tests use http.NoBody instead of nil --- .golangci.yml | 6 + app_test.go | 174 +++++++++--------- bind_test.go | 11 +- ctx_test.go | 68 +++---- middleware/adaptor/adaptor_test.go | 2 +- middleware/basicauth/basicauth_test.go | 5 +- middleware/cache/cache_test.go | 109 +++++------ middleware/compress/compress_test.go | 15 +- middleware/cors/cors_test.go | 3 +- middleware/csrf/csrf_test.go | 11 +- middleware/earlydata/earlydata_test.go | 1 - .../encryptcookie/encryptcookie_test.go | 3 +- middleware/envvar/envvar_test.go | 1 - middleware/etag/etag_test.go | 17 +- middleware/expvar/expvar_test.go | 11 +- middleware/favicon/favicon_test.go | 21 +-- middleware/filesystem/filesystem_test.go | 13 +- middleware/healthcheck/healthcheck_test.go | 7 +- middleware/helmet/helmet_test.go | 17 +- middleware/idempotency/idempotency_test.go | 1 - middleware/keyauth/keyauth_test.go | 17 +- middleware/limiter/limiter_test.go | 113 ++++++------ middleware/logger/logger_test.go | 49 +++-- middleware/pprof/pprof_test.go | 21 ++- middleware/proxy/proxy_test.go | 47 ++--- middleware/recover/recover_test.go | 7 +- middleware/redirect/redirect_test.go | 1 - middleware/requestid/requestid_test.go | 9 +- middleware/rewrite/rewrite_test.go | 1 - middleware/skip/skip_test.go | 7 +- middleware/timeout/timeout_test.go | 9 +- mount_test.go | 5 +- router_test.go | 68 +++---- 33 files changed, 432 insertions(+), 418 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index de70317d47..1f55c987fb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -162,6 +162,12 @@ linters-settings: issues: exclude-use-default: false + exclude-rules: + # Exclude some linters from running on tests files. + - path: _test\.go + linters: + - bodyclose + linters: disable: - spancheck # opentelemetry, irrelevant diff --git a/app_test.go b/app_test.go index 46d05bd0d1..3b505049ba 100644 --- a/app_test.go +++ b/app_test.go @@ -2,7 +2,7 @@ // 🤖 Github Repository: https://github.com/gofiber/fiber // 📌 API Documentation: https://docs.gofiber.io -//nolint:bodyclose, goconst // Much easier to just ignore memory leaks in tests +//nolint:goconst // Much easier to just ignore memory leaks in tests package fiber import ( @@ -37,7 +37,7 @@ func testEmptyHandler(_ Ctx) error { func testStatus200(t *testing.T, app *App, url, method string) { t.Helper() - req := httptest.NewRequest(method, url, nil) + req := httptest.NewRequest(method, url, http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -67,41 +67,41 @@ func Test_App_MethodNotAllowed(t *testing.T) { app.Options("/", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest(MethodPost, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, "", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "POST, OPTIONS", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "POST, OPTIONS", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodPut, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodPut, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "POST, OPTIONS", resp.Header.Get(HeaderAllow)) app.Get("/", testEmptyHandler) - resp, err = app.Test(httptest.NewRequest(MethodTrace, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodTrace, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "GET, POST, OPTIONS", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "GET, POST, OPTIONS", resp.Header.Get(HeaderAllow)) app.Head("/", testEmptyHandler) - resp, err = app.Test(httptest.NewRequest(MethodPut, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodPut, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "GET, HEAD, POST, OPTIONS", resp.Header.Get(HeaderAllow)) @@ -117,7 +117,7 @@ func Test_App_Custom_Middleware_404_Should_Not_SetMethodNotAllowed(t *testing.T) app.Post("/", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) @@ -127,7 +127,7 @@ func Test_App_Custom_Middleware_404_Should_Not_SetMethodNotAllowed(t *testing.T) g.Post("/", testEmptyHandler) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/with-next", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/with-next", http.NoBody)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } @@ -143,7 +143,7 @@ func Test_App_ServerErrorHandler_SmallReadBuffer(t *testing.T) { panic(errors.New("should never called")) }) - request := httptest.NewRequest(MethodGet, "/", nil) + request := httptest.NewRequest(MethodGet, "/", http.NoBody) logHeaderSlice := make([]string, 5000) request.Header.Set("Very-Long-Header", strings.Join(logHeaderSlice, "-")) _, err := app.Test(request) @@ -164,7 +164,7 @@ func Test_App_Errors(t *testing.T) { return errors.New("hi, i'm an error") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 500, resp.StatusCode, "Status code") @@ -212,23 +212,23 @@ func Test_App_CustomConstraint(t *testing.T) { return c.SendString("test") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/test2", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/test2", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/c", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/c", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/cc", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/cc", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/cc", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/cc", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") } @@ -245,7 +245,7 @@ func Test_App_ErrorHandler_Custom(t *testing.T) { return errors.New("hi, i'm an error") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -275,7 +275,7 @@ func Test_App_ErrorHandler_HandlerStack(t *testing.T) { return errors.New("0: GET error") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 500, resp.StatusCode, "Status code") @@ -301,7 +301,7 @@ func Test_App_ErrorHandler_RouteStack(t *testing.T) { return errors.New("0: GET error") // [1] return to USE }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 500, resp.StatusCode, "Status code") @@ -352,7 +352,7 @@ func Test_App_Nested_Params(t *testing.T) { return c.Status(200).Send([]byte("Good job")) }) - req := httptest.NewRequest(MethodGet, "/test/john/test/doe", nil) + req := httptest.NewRequest(MethodGet, "/test/john/test/doe", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -379,15 +379,15 @@ func Test_App_Use_Params(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/john/doe", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/john/doe", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -416,7 +416,7 @@ func Test_App_Use_UnescapedPath(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/cR%C3%A9eR/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/cR%C3%A9eR/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -426,7 +426,7 @@ func Test_App_Use_UnescapedPath(t *testing.T) { require.Equal(t, "اختبار", app.getString(body)) // with lowercase letters - resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") } @@ -440,19 +440,19 @@ func Test_App_Use_CaseSensitive(t *testing.T) { }) // wrong letters in the requested route -> 404 - resp, err := app.Test(httptest.NewRequest(MethodGet, "/AbC", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/AbC", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") // right letters in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // check the detected path when the case insensitive recognition is activated app.config.CaseSensitive = false // check the case sensitive feature - resp, err = app.Test(httptest.NewRequest(MethodGet, "/AbC", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/AbC", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -476,22 +476,22 @@ func Test_App_Not_Use_StrictRouting(t *testing.T) { }) // wrong path in the requested route -> 404 - resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // right path in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // wrong path with group in the requested route -> 404 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // right path with group in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -509,7 +509,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { return c.SendString(c.Path()) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/john", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/john", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -517,7 +517,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { require.NoError(t, err) require.Equal(t, "/john", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -525,7 +525,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { require.NoError(t, err) require.Equal(t, "/doe", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/john", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/john", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -533,7 +533,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { require.NoError(t, err) require.Equal(t, "/test/john", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/doe", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/doe", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -556,22 +556,22 @@ func Test_App_Use_StrictRouting(t *testing.T) { }) // wrong path in the requested route -> 404 - resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") // right path in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // wrong path with group in the requested route -> 404 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") // right path with group in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -591,15 +591,15 @@ func Test_App_Add_Method_Test(t *testing.T) { app.Add([]string{"JOHN"}, "/doe", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest("JOHN", "/doe", nil)) + resp, err := app.Test(httptest.NewRequest("JOHN", "/doe", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusMethodNotAllowed, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest("UNKNOWN", "/doe", nil)) + resp, err = app.Test(httptest.NewRequest("UNKNOWN", "/doe", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotImplemented, resp.StatusCode, "Status code") @@ -617,7 +617,7 @@ func Test_App_GETOnly(t *testing.T) { return c.SendString("Hello 👋!") }) - req := httptest.NewRequest(MethodPost, "/", nil) + req := httptest.NewRequest(MethodPost, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusMethodNotAllowed, resp.StatusCode, "Status code") @@ -637,7 +637,7 @@ func Test_App_Use_Params_Group(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john/doe/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john/doe/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") } @@ -654,7 +654,7 @@ func Test_App_Chaining(t *testing.T) { // check handler count for registered HEAD route require.Len(t, app.stack[app.methodInt(MethodHead)][0].Handlers, 5, "app.Test(req)") - req := httptest.NewRequest(MethodPost, "/john", nil) + req := httptest.NewRequest(MethodPost, "/john", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -664,7 +664,7 @@ func Test_App_Chaining(t *testing.T) { return c.SendStatus(203) }) - req = httptest.NewRequest(MethodGet, "/test", nil) + req = httptest.NewRequest(MethodGet, "/test", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -696,7 +696,7 @@ func Test_App_Order(t *testing.T) { return nil }) - req := httptest.NewRequest(MethodGet, "/test", nil) + req := httptest.NewRequest(MethodGet, "/test", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -909,7 +909,7 @@ func Test_App_Static_Index_Default(t *testing.T) { app.Static("", "./.github/") app.Static("test", "", Static{Index: "index.html"}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -919,7 +919,7 @@ func Test_App_Static_Index_Default(t *testing.T) { require.NoError(t, err) require.Contains(t, string(body), "Hello, World!") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/not-found", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/not-found", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -936,7 +936,7 @@ func Test_App_Static_Direct(t *testing.T) { app.Static("/", "./.github") - resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -946,7 +946,7 @@ func Test_App_Static_Direct(t *testing.T) { require.NoError(t, err) require.Contains(t, string(body), "Hello, World!") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/testdata/testRoutes.json", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/testdata/testRoutes.json", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -964,7 +964,7 @@ func Test_App_Static_MaxAge(t *testing.T) { app.Static("/", "./.github", Static{MaxAge: 100}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -983,11 +983,11 @@ func Test_App_Static_Custom_CacheControl(t *testing.T) { return nil }}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, "no-cache, no-store, must-revalidate", resp.Header.Get(HeaderCacheControl), "CacheControl Control") - normalResp, normalErr := app.Test(httptest.NewRequest(MethodGet, "/config.yml", nil)) + normalResp, normalErr := app.Test(httptest.NewRequest(MethodGet, "/config.yml", http.NoBody)) require.NoError(t, normalErr, "app.Test(req)") require.Equal(t, "", normalResp.Header.Get(HeaderCacheControl), "CacheControl Control") } @@ -998,7 +998,7 @@ func Test_App_Static_Download(t *testing.T) { app.Static("/fiber.png", "./.github/testdata/fs/img/fiber.png", Static{Download: true}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/fiber.png", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/fiber.png", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -1017,7 +1017,7 @@ func Test_App_Static_Group(t *testing.T) { grp.Static("/v2", "./.github/index.html") - req := httptest.NewRequest(MethodGet, "/v1/v2", nil) + req := httptest.NewRequest(MethodGet, "/v1/v2", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1028,7 +1028,7 @@ func Test_App_Static_Group(t *testing.T) { grp = app.Group("/v2") grp.Static("/v3*", "./.github/index.html") - req = httptest.NewRequest(MethodGet, "/v2/v3/john/doe", nil) + req = httptest.NewRequest(MethodGet, "/v2/v3/john/doe", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1041,7 +1041,7 @@ func Test_App_Static_Wildcard(t *testing.T) { app.Static("*", "./.github/index.html") - req := httptest.NewRequest(MethodGet, "/yesyes/john/doe", nil) + req := httptest.NewRequest(MethodGet, "/yesyes/john/doe", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1058,7 +1058,7 @@ func Test_App_Static_Prefix_Wildcard(t *testing.T) { app.Static("/test/*", "./.github/index.html") - req := httptest.NewRequest(MethodGet, "/test/john/doe", nil) + req := httptest.NewRequest(MethodGet, "/test/john/doe", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1067,7 +1067,7 @@ func Test_App_Static_Prefix_Wildcard(t *testing.T) { app.Static("/my/nameisjohn*", "./.github/index.html") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/my/nameisjohn/no/its/not", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/my/nameisjohn/no/its/not", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -1082,7 +1082,7 @@ func Test_App_Static_Prefix(t *testing.T) { app := New() app.Static("/john", "./.github") - req := httptest.NewRequest(MethodGet, "/john/index.html", nil) + req := httptest.NewRequest(MethodGet, "/john/index.html", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1091,7 +1091,7 @@ func Test_App_Static_Prefix(t *testing.T) { app.Static("/prefix", "./.github/testdata") - req = httptest.NewRequest(MethodGet, "/prefix/index.html", nil) + req = httptest.NewRequest(MethodGet, "/prefix/index.html", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1100,7 +1100,7 @@ func Test_App_Static_Prefix(t *testing.T) { app.Static("/single", "./.github/testdata/testRoutes.json") - req = httptest.NewRequest(MethodGet, "/single", nil) + req = httptest.NewRequest(MethodGet, "/single", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1112,7 +1112,7 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app := New() app.Static("/john", "./.github") - req := httptest.NewRequest(MethodGet, "/john/", nil) + req := httptest.NewRequest(MethodGet, "/john/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1121,7 +1121,7 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app.Static("/john_without_index", "./.github/testdata/fs/css") - req = httptest.NewRequest(MethodGet, "/john_without_index/", nil) + req = httptest.NewRequest(MethodGet, "/john_without_index/", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") @@ -1130,14 +1130,14 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app.Static("/john/", "./.github") - req = httptest.NewRequest(MethodGet, "/john/", nil) + req = httptest.NewRequest(MethodGet, "/john/", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) require.Equal(t, MIMETextHTMLCharsetUTF8, resp.Header.Get(HeaderContentType)) - req = httptest.NewRequest(MethodGet, "/john", nil) + req = httptest.NewRequest(MethodGet, "/john", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1146,7 +1146,7 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app.Static("/john_without_index/", "./.github/testdata/fs/css") - req = httptest.NewRequest(MethodGet, "/john_without_index/", nil) + req = httptest.NewRequest(MethodGet, "/john_without_index/", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") @@ -1168,7 +1168,7 @@ func Test_App_Static_Next(t *testing.T) { }) t.Run("app.Static is skipped: invoking Get handler", func(t *testing.T) { - req := httptest.NewRequest(MethodGet, "/", nil) + req := httptest.NewRequest(MethodGet, "/", http.NoBody) req.Header.Set("X-Custom-Header", "skip") resp, err := app.Test(req) require.NoError(t, err) @@ -1182,7 +1182,7 @@ func Test_App_Static_Next(t *testing.T) { }) t.Run("app.Static is not skipped: serving index.html", func(t *testing.T) { - req := httptest.NewRequest(MethodGet, "/", nil) + req := httptest.NewRequest(MethodGet, "/", http.NoBody) req.Header.Set("X-Custom-Header", "don't skip") resp, err := app.Test(req) require.NoError(t, err) @@ -1213,7 +1213,7 @@ func Test_App_Mixed_Routes_WithSameLen(t *testing.T) { }) // match get route - req := httptest.NewRequest(MethodGet, "/foobar", nil) + req := httptest.NewRequest(MethodGet, "/foobar", http.NoBody) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1226,7 +1226,7 @@ func Test_App_Mixed_Routes_WithSameLen(t *testing.T) { require.Equal(t, "FOO_BAR", string(body)) // match static route - req = httptest.NewRequest(MethodGet, "/tesbar", nil) + req = httptest.NewRequest(MethodGet, "/tesbar", http.NoBody) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1299,13 +1299,13 @@ func Test_App_Group(t *testing.T) { api := grp.Group("/v1") api.Post("/", dummyHandler) - resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") // require.Equal(t, "/test/v1", resp.Header.Get("Location"), "Location") api.Get("/users", dummyHandler) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") // require.Equal(t, "/test/v1/users", resp.Header.Get("Location"), "Location") @@ -1340,21 +1340,21 @@ func Test_App_Route(t *testing.T) { register.Route("/v1").Get(dummyHandler).Post(dummyHandler) - resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1", nil)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") register.Route("/v1").Route("/v2").Route("/v3").Get(dummyHandler).Trace(dummyHandler) - resp, err = app.Test(httptest.NewRequest(MethodTrace, "/test/v1/v2/v3", nil)) + resp, err = app.Test(httptest.NewRequest(MethodTrace, "/test/v1/v2/v3", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/v2/v3", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/v2/v3", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") } @@ -1391,7 +1391,7 @@ func Test_App_Next_Method(t *testing.T) { return err }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") } @@ -1428,7 +1428,7 @@ func Test_Test_Timeout(t *testing.T) { app.Get("/", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil), -1) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody), -1) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1437,7 +1437,7 @@ func Test_Test_Timeout(t *testing.T) { return nil }) - _, err = app.Test(httptest.NewRequest(MethodGet, "/timeout", nil), 20) + _, err = app.Test(httptest.NewRequest(MethodGet, "/timeout", http.NoBody), 20) require.Error(t, err, "app.Test(req)") } @@ -1637,7 +1637,7 @@ func Test_App_Error_In_Fasthttp_Server(t *testing.T) { } app.server.GetOnly = true - resp, err := app.Test(httptest.NewRequest(MethodPost, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 500, resp.StatusCode) } @@ -1648,13 +1648,13 @@ func Test_App_New_Test_Parallel(t *testing.T) { t.Run("Test_App_New_Test_Parallel_1", func(t *testing.T) { t.Parallel() app := New(Config{Immutable: true}) - _, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err) }) t.Run("Test_App_New_Test_Parallel_2", func(t *testing.T) { t.Parallel() app := New(Config{Immutable: true}) - _, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err) }) } diff --git a/bind_test.go b/bind_test.go index f20255bc53..59186abab5 100644 --- a/bind_test.go +++ b/bind_test.go @@ -1,4 +1,4 @@ -//nolint:wrapcheck,tagliatelle,bodyclose // We must not wrap errors in tests +//nolint:wrapcheck,tagliatelle // We must not wrap errors in tests package fiber import ( @@ -7,6 +7,7 @@ import ( "encoding/json" "errors" "fmt" + "net/http" "net/http/httptest" "reflect" "testing" @@ -1099,9 +1100,9 @@ func Test_Bind_URI(t *testing.T) { require.Equal(t, uint(222), d.RoleID) return nil }) - _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", http.NoBody)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", http.NoBody)) require.NoError(t, err) } @@ -1120,9 +1121,9 @@ func Test_Bind_URI_Map(t *testing.T) { require.Equal(t, uint(222), d["roleId"]) return nil }) - _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", http.NoBody)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", http.NoBody)) require.NoError(t, err) } diff --git a/ctx_test.go b/ctx_test.go index bef906ea3c..3a266a9491 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -2,7 +2,6 @@ // 🤖 Github Repository: https://github.com/gofiber/fiber // 📌 API Documentation: https://docs.gofiber.io -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package fiber import ( @@ -18,6 +17,7 @@ import ( "io" "mime/multipart" "net" + "net/http" "net/http/httptest" "os" "path/filepath" @@ -856,7 +856,7 @@ func Test_Ctx_UserContext_Multiple_Requests(t *testing.T) { i := i t.Run(fmt.Sprintf("request_%d", i), func(t *testing.T) { t.Parallel() - resp, err := app.Test(httptest.NewRequest(MethodGet, fmt.Sprintf("/?input=%d", i), nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, fmt.Sprintf("/?input=%d", i), http.NoBody)) require.NoError(t, err, "Unexpected error from response") require.Equal(t, StatusOK, resp.StatusCode, "context.Context returned from c.UserContext() is reused") @@ -1740,7 +1740,7 @@ func Test_Ctx_PortInHandler(t *testing.T) { return c.SendString(c.Port()) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/port", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/port", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -2077,7 +2077,7 @@ func Test_Ctx_Locals(t *testing.T) { require.Equal(t, "doe", c.Locals("john")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2099,7 +2099,7 @@ func Test_Ctx_Locals_Generic(t *testing.T) { require.Equal(t, 0, Locals[int](c, "isHuman")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2122,7 +2122,7 @@ func Test_Ctx_Locals_GenericCustomStruct(t *testing.T) { require.Equal(t, User{"john", 18}, Locals[User](c, "user")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2173,7 +2173,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { }) // Test without TLS handler - resp, err := app.Test(httptest.NewRequest(MethodGet, "/ServerName", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/ServerName", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -2191,7 +2191,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { }} // Test ServerName - resp, err = app.Test(httptest.NewRequest(MethodGet, "/ServerName", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/ServerName", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) @@ -2199,7 +2199,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { require.Equal(t, []byte("example.golang"), body) // Test SignatureSchemes - resp, err = app.Test(httptest.NewRequest(MethodGet, "/SignatureSchemes", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/SignatureSchemes", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) @@ -2207,7 +2207,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { require.Equal(t, "["+strconv.Itoa(pssWithSHA256)+"]", string(body)) // Test SupportedVersions - resp, err = app.Test(httptest.NewRequest(MethodGet, "/SupportedVersions", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/SupportedVersions", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) @@ -2322,23 +2322,23 @@ func Test_Ctx_Params(t *testing.T) { require.Equal(t, "first", c.Params("Id")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/im/a/cookie", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/im/a/cookie", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/1111/blafasel/2222", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/1111/blafasel/2222", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test4", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test4", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test5/first/second", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test5/first/second", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2356,11 +2356,11 @@ func Test_Ctx_Params_Case_Sensitive(t *testing.T) { require.Equal(t, "second", c.Params("Id")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/first/second", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/first/second", http.NoBody)) require.NoError(t, err) require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2409,7 +2409,7 @@ func Test_Ctx_Path(t *testing.T) { require.Equal(t, "/اختبار/", c.Path("/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1/")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/specialChars/cr%C3%A9er", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/specialChars/cr%C3%A9er", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -3128,7 +3128,7 @@ func Test_Ctx_Route(t *testing.T) { require.Equal(t, "/test", c.Route().Path) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -3147,7 +3147,7 @@ func Test_Ctx_RouteNormalized(t *testing.T) { require.Equal(t, "/test", c.Route().Path) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "//test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "//test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") } @@ -3384,7 +3384,7 @@ func Test_Ctx_SendFile_404(t *testing.T) { return err }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, StatusNotFound, resp.StatusCode) } @@ -3424,11 +3424,11 @@ func Test_Ctx_SendFile_Immutable(t *testing.T) { t.Run(endpoint, func(t *testing.T) { t.Parallel() // 1st try - resp, err := app.Test(httptest.NewRequest(MethodGet, endpoint, nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, endpoint, http.NoBody)) require.NoError(t, err) require.Equal(t, StatusOK, resp.StatusCode) // 2nd try - resp, err = app.Test(httptest.NewRequest(MethodGet, endpoint, nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, endpoint, http.NoBody)) require.NoError(t, err) require.Equal(t, StatusOK, resp.StatusCode) }) @@ -3446,9 +3446,9 @@ func Test_Ctx_SendFile_RestoreOriginalURL(t *testing.T) { return err }) - _, err1 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", nil)) + _, err1 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", http.NoBody)) // second request required to confirm with zero allocation - _, err2 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", nil)) + _, err2 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", http.NoBody)) require.NoError(t, err1) require.NoError(t, err2) @@ -3761,7 +3761,7 @@ func Test_Ctx_Next(t *testing.T) { c.Set("X-Next-Result", "Works") return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.Equal(t, "Works", resp.Header.Get("X-Next-Result")) @@ -3776,7 +3776,7 @@ func Test_Ctx_Next_Error(t *testing.T) { return ErrNotFound }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") require.Equal(t, "Works", resp.Header.Get("X-Next-Result")) @@ -4018,7 +4018,7 @@ func Test_Ctx_RestartRouting(t *testing.T) { } return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.Equal(t, 3, calls, "Number of calls") @@ -4043,7 +4043,7 @@ func Test_Ctx_RestartRoutingWithChangedPath(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.False(t, executedOldHandler, "Executed old handler") @@ -4066,7 +4066,7 @@ func Test_Ctx_RestartRoutingWithChangedPathAndCatchAll(t *testing.T) { return ErrNotFound }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -4813,16 +4813,16 @@ func TestCtx_ParamsInt(t *testing.T) { return nil }) - _, err := app.Test(httptest.NewRequest(MethodGet, "/test/1111", nil)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/test/1111", http.NoBody)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/testnoint/xd", nil)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/testnoint/xd", http.NoBody)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", nil)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", http.NoBody)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", nil)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", http.NoBody)) require.NoError(t, err) } diff --git a/middleware/adaptor/adaptor_test.go b/middleware/adaptor/adaptor_test.go index 2982fb4042..544b5baabb 100644 --- a/middleware/adaptor/adaptor_test.go +++ b/middleware/adaptor/adaptor_test.go @@ -1,4 +1,4 @@ -//nolint:bodyclose, contextcheck, revive // Much easier to just ignore memory leaks in tests +//nolint:contextcheck, revive // Much easier to just ignore memory leaks in tests package adaptor import ( diff --git a/middleware/basicauth/basicauth_test.go b/middleware/basicauth/basicauth_test.go index 421fcfd8dd..0f8a86e660 100644 --- a/middleware/basicauth/basicauth_test.go +++ b/middleware/basicauth/basicauth_test.go @@ -4,6 +4,7 @@ import ( "encoding/base64" "fmt" "io" + "net/http" "net/http/httptest" "testing" @@ -22,7 +23,7 @@ func Test_BasicAuth_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -75,7 +76,7 @@ func Test_Middleware_BasicAuth(t *testing.T) { // Base64 encode credentials for http auth header creds := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", tt.username, tt.password))) - req := httptest.NewRequest(fiber.MethodGet, "/testauth", nil) + req := httptest.NewRequest(fiber.MethodGet, "/testauth", http.NoBody) req.Header.Add("Authorization", "Basic "+creds) resp, err := app.Test(req) require.NoError(t, err) diff --git a/middleware/cache/cache_test.go b/middleware/cache/cache_test.go index 1beee76d62..e21d43a49d 100644 --- a/middleware/cache/cache_test.go +++ b/middleware/cache/cache_test.go @@ -7,6 +7,7 @@ import ( "fmt" "io" "math" + "net/http" "net/http/httptest" "os" "strconv" @@ -35,10 +36,10 @@ func Test_Cache_CacheControl(t *testing.T) { return c.SendString("Hello, World!") }) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "public, max-age=10", resp.Header.Get(fiber.HeaderCacheControl)) } @@ -53,7 +54,7 @@ func Test_Cache_Expired(t *testing.T) { return c.SendString(strconv.FormatInt(time.Now().UnixNano(), 10)) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -61,7 +62,7 @@ func Test_Cache_Expired(t *testing.T) { // Sleep until the cache is expired time.Sleep(3 * time.Second) - respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) bodyCached, err := io.ReadAll(respCached.Body) require.NoError(t, err) @@ -71,7 +72,7 @@ func Test_Cache_Expired(t *testing.T) { } // Next response should be also cached - respCachedNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + respCachedNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) bodyCachedNextRound, err := io.ReadAll(respCachedNextRound.Body) require.NoError(t, err) @@ -92,11 +93,11 @@ func Test_Cache(t *testing.T) { return c.SendString(now) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err) - cachedReq := httptest.NewRequest(fiber.MethodGet, "/", nil) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) @@ -120,7 +121,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { }) // Request id = 1 - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err) body, err := io.ReadAll(resp.Body) @@ -130,7 +131,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { // Response cached, entry id = 1 // Request id = 2 without Cache-Control: no-cache - cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) cachedBody, err := io.ReadAll(cachedResp.Body) @@ -140,7 +141,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { // Response not cached, returns cached response, entry id = 1 // Request id = 2 with Cache-Control: no-cache - noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) noCacheReq.Header.Set(fiber.HeaderCacheControl, noCache) noCacheResp, err := app.Test(noCacheReq) require.NoError(t, err) @@ -152,7 +153,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { /* Check Test_Cache_WithETagAndNoCacheRequestDirective */ // Request id = 2 with Cache-Control: no-cache again - noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) noCacheReq1.Header.Set(fiber.HeaderCacheControl, noCache) noCacheResp1, err := app.Test(noCacheReq1) require.NoError(t, err) @@ -163,7 +164,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { // Response cached, returns updated response, entry = 2 // Request id = 1 without Cache-Control: no-cache - cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", nil) + cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) cachedResp1, err := app.Test(cachedReq1) require.NoError(t, err) cachedBody1, err := io.ReadAll(cachedResp1.Body) @@ -188,7 +189,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { }) // Request id = 1 - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("X-Cache")) @@ -199,7 +200,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { etagToken := resp.Header.Get("Etag") // Request id = 2 with ETag but without Cache-Control: no-cache - cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) cachedReq.Header.Set(fiber.HeaderIfNoneMatch, etagToken) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) @@ -208,7 +209,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { // Response not cached, returns cached response, entry id = 1, status not modified // Request id = 2 with ETag and Cache-Control: no-cache - noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) noCacheReq.Header.Set(fiber.HeaderCacheControl, noCache) noCacheReq.Header.Set(fiber.HeaderIfNoneMatch, etagToken) noCacheResp, err := app.Test(noCacheReq) @@ -221,7 +222,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { etagToken = noCacheResp.Header.Get("Etag") // Request id = 2 with ETag and Cache-Control: no-cache again - noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) noCacheReq1.Header.Set(fiber.HeaderCacheControl, noCache) noCacheReq1.Header.Set(fiber.HeaderIfNoneMatch, etagToken) noCacheResp1, err := app.Test(noCacheReq1) @@ -231,7 +232,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { // Response cached, returns updated response, entry id = 2, status not modified // Request id = 1 without ETag and Cache-Control: no-cache - cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", nil) + cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) cachedResp1, err := app.Test(cachedReq1) require.NoError(t, err) require.Equal(t, cacheHit, cachedResp1.Header.Get("X-Cache")) @@ -251,7 +252,7 @@ func Test_Cache_WithNoStoreRequestDirective(t *testing.T) { }) // Request id = 2 - noStoreReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) + noStoreReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) noStoreReq.Header.Set(fiber.HeaderCacheControl, noStore) noStoreResp, err := app.Test(noStoreReq) require.NoError(t, err) @@ -278,7 +279,7 @@ func Test_Cache_WithSeveralRequests(t *testing.T) { for runs := 0; runs < 10; runs++ { for i := 0; i < 10; i++ { func(id int) { - rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, fmt.Sprintf("/%d", id), nil)) + rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, fmt.Sprintf("/%d", id), http.NoBody)) require.NoError(t, err) defer func(body io.ReadCloser) { @@ -311,11 +312,11 @@ func Test_Cache_Invalid_Expiration(t *testing.T) { return c.SendString(now) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err) - cachedReq := httptest.NewRequest(fiber.MethodGet, "/", nil) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) @@ -342,25 +343,25 @@ func Test_Cache_Get(t *testing.T) { return c.SendString(fiber.Query[string](c, "cache")) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "12345", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) @@ -384,25 +385,25 @@ func Test_Cache_Post(t *testing.T) { return c.SendString(fiber.Query[string](c, "cache")) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", http.NoBody)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) @@ -420,14 +421,14 @@ func Test_Cache_NothingToCache(t *testing.T) { return c.SendString(time.Now().String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) time.Sleep(500 * time.Millisecond) - respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) bodyCached, err := io.ReadAll(respCached.Body) require.NoError(t, err) @@ -457,22 +458,22 @@ func Test_Cache_CustomNext(t *testing.T) { return c.Status(fiber.StatusInternalServerError).SendString(time.Now().String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) - respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) bodyCached, err := io.ReadAll(respCached.Body) require.NoError(t, err) require.True(t, bytes.Equal(body, bodyCached)) require.NotEmpty(t, respCached.Header.Get(fiber.HeaderCacheControl)) - _, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/error", nil)) + _, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/error", http.NoBody)) require.NoError(t, err) - errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", nil)) + errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", http.NoBody)) require.NoError(t, err) require.Empty(t, errRespCached.Header.Get(fiber.HeaderCacheControl)) } @@ -491,7 +492,7 @@ func Test_CustomKey(t *testing.T) { return c.SendString("hi") }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) _, err := app.Test(req) require.NoError(t, err) require.True(t, called) @@ -516,7 +517,7 @@ func Test_CustomExpiration(t *testing.T) { return c.SendString(strconv.FormatInt(time.Now().UnixNano(), 10)) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.True(t, called) require.Equal(t, 1, newCacheTime) @@ -524,7 +525,7 @@ func Test_CustomExpiration(t *testing.T) { // Sleep until the cache is expired time.Sleep(1 * time.Second) - cachedResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + cachedResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) @@ -537,7 +538,7 @@ func Test_CustomExpiration(t *testing.T) { } // Next response should be cached - cachedRespNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + cachedRespNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) cachedBodyNextRound, err := io.ReadAll(cachedRespNextRound.Body) require.NoError(t, err) @@ -560,12 +561,12 @@ func Test_AdditionalE2EResponseHeaders(t *testing.T) { return c.SendString("hi") }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err) require.Equal(t, "foobar", resp.Header.Get("X-Foobar")) - req = httptest.NewRequest(fiber.MethodGet, "/", nil) + req = httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) resp, err = app.Test(req) require.NoError(t, err) require.Equal(t, "foobar", resp.Header.Get("X-Foobar")) @@ -595,19 +596,19 @@ func Test_CacheHeader(t *testing.T) { return c.Status(fiber.StatusInternalServerError).SendString(time.Now().String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("X-Cache")) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, cacheHit, resp.Header.Get("X-Cache")) - resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", http.NoBody)) require.NoError(t, err) require.Equal(t, cacheUnreachable, resp.Header.Get("X-Cache")) - errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", nil)) + errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", http.NoBody)) require.NoError(t, err) require.Equal(t, cacheUnreachable, errRespCached.Header.Get("X-Cache")) } @@ -624,12 +625,12 @@ func Test_Cache_WithHead(t *testing.T) { } app.Route("/").Get(handler).Head(handler) - req := httptest.NewRequest(fiber.MethodHead, "/", nil) + req := httptest.NewRequest(fiber.MethodHead, "/", http.NoBody) resp, err := app.Test(req) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("X-Cache")) - cachedReq := httptest.NewRequest(fiber.MethodHead, "/", nil) + cachedReq := httptest.NewRequest(fiber.MethodHead, "/", http.NoBody) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) require.Equal(t, cacheHit, cachedResp.Header.Get("X-Cache")) @@ -653,28 +654,28 @@ func Test_Cache_WithHeadThenGet(t *testing.T) { } app.Route("/").Get(handler).Head(handler) - headResp, err := app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", nil)) + headResp, err := app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", http.NoBody)) require.NoError(t, err) headBody, err := io.ReadAll(headResp.Body) require.NoError(t, err) require.Equal(t, "", string(headBody)) require.Equal(t, cacheMiss, headResp.Header.Get("X-Cache")) - headResp, err = app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", nil)) + headResp, err = app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", http.NoBody)) require.NoError(t, err) headBody, err = io.ReadAll(headResp.Body) require.NoError(t, err) require.Equal(t, "", string(headBody)) require.Equal(t, cacheHit, headResp.Header.Get("X-Cache")) - getResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", nil)) + getResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", http.NoBody)) require.NoError(t, err) getBody, err := io.ReadAll(getResp.Body) require.NoError(t, err) require.Equal(t, "123", string(getBody)) require.Equal(t, cacheMiss, getResp.Header.Get("X-Cache")) - getResp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", nil)) + getResp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", http.NoBody)) require.NoError(t, err) getBody, err = io.ReadAll(getResp.Body) require.NoError(t, err) @@ -695,7 +696,7 @@ func Test_CustomCacheHeader(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("Cache-Status")) } @@ -742,7 +743,7 @@ func Test_Cache_MaxBytesOrder(t *testing.T) { } for idx, tcase := range cases { - rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], nil)) + rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], http.NoBody)) require.NoError(t, err) require.Equal(t, tcase[1], rsp.Header.Get("X-Cache"), fmt.Sprintf("Case %v", idx)) } @@ -777,7 +778,7 @@ func Test_Cache_MaxBytesSizes(t *testing.T) { } for idx, tcase := range cases { - rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], nil)) + rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], http.NoBody)) require.NoError(t, err) require.Equal(t, tcase[1], rsp.Header.Get("X-Cache"), fmt.Sprintf("Case %v", idx)) } diff --git a/middleware/compress/compress_test.go b/middleware/compress/compress_test.go index 2d85e790c6..3bdc71da0b 100644 --- a/middleware/compress/compress_test.go +++ b/middleware/compress/compress_test.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io" + "net/http" "net/http/httptest" "os" "testing" @@ -34,7 +35,7 @@ func Test_Compress_Gzip(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req) @@ -65,7 +66,7 @@ func Test_Compress_Different_Level(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req) @@ -91,7 +92,7 @@ func Test_Compress_Deflate(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "deflate") resp, err := app.Test(req) @@ -115,7 +116,7 @@ func Test_Compress_Brotli(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "br") resp, err := app.Test(req, 10000) @@ -139,7 +140,7 @@ func Test_Compress_Disabled(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "br") resp, err := app.Test(req) @@ -163,7 +164,7 @@ func Test_Compress_Next_Error(t *testing.T) { return errors.New("next error") }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req) @@ -186,7 +187,7 @@ func Test_Compress_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 3d3ae8c655..1ba213fcdc 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -1,6 +1,7 @@ package cors import ( + "net/http" "net/http/httptest" "strings" "testing" @@ -339,7 +340,7 @@ func Test_CORS_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } diff --git a/middleware/csrf/csrf_test.go b/middleware/csrf/csrf_test.go index 99cbf85e48..277ac3f002 100644 --- a/middleware/csrf/csrf_test.go +++ b/middleware/csrf/csrf_test.go @@ -1,6 +1,7 @@ package csrf import ( + "net/http" "net/http/httptest" "strings" "testing" @@ -374,7 +375,7 @@ func Test_CSRF_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -948,7 +949,7 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // return c.SendStatus(fiber.StatusOK) // }) -// resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) +// resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) // require.NoError(t, err) // require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -963,11 +964,11 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // fmt.Println("token", token) -// getReq := httptest.NewRequest(fiber.MethodGet, "/", nil) +// getReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) // getReq.Header.Set(HeaderName, token) // resp, err = app.Test(getReq) -// getReq = httptest.NewRequest(fiber.MethodGet, "/test", nil) +// getReq = httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody) // getReq.Header.Set("X-Requested-With", "XMLHttpRequest") // getReq.Header.Set(fiber.HeaderCacheControl, "no") // getReq.Header.Set(HeaderName, token) @@ -978,7 +979,7 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // getReq.Header.Del(HeaderName) // resp, err = app.Test(getReq) -// postReq := httptest.NewRequest(fiber.MethodPost, "/", nil) +// postReq := httptest.NewRequest(fiber.MethodPost, "/", http.NoBody) // postReq.Header.Set("X-Requested-With", "XMLHttpRequest") // postReq.Header.Set(HeaderName, token) // resp, err = app.Test(postReq) diff --git a/middleware/earlydata/earlydata_test.go b/middleware/earlydata/earlydata_test.go index 9ec76d6b03..4c6d76258e 100644 --- a/middleware/earlydata/earlydata_test.go +++ b/middleware/earlydata/earlydata_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package earlydata_test import ( diff --git a/middleware/encryptcookie/encryptcookie_test.go b/middleware/encryptcookie/encryptcookie_test.go index ee7ca9ae60..046ba9ca1b 100644 --- a/middleware/encryptcookie/encryptcookie_test.go +++ b/middleware/encryptcookie/encryptcookie_test.go @@ -2,6 +2,7 @@ package encryptcookie import ( "encoding/base64" + "net/http" "net/http/httptest" "testing" @@ -92,7 +93,7 @@ func Test_Encrypt_Cookie_Next(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "SomeThing", resp.Cookies()[0].Value) } diff --git a/middleware/envvar/envvar_test.go b/middleware/envvar/envvar_test.go index c4964884a1..8c2fbeb05b 100644 --- a/middleware/envvar/envvar_test.go +++ b/middleware/envvar/envvar_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package envvar import ( diff --git a/middleware/etag/etag_test.go b/middleware/etag/etag_test.go index 9769639cb1..ebdea0f422 100644 --- a/middleware/etag/etag_test.go +++ b/middleware/etag/etag_test.go @@ -3,6 +3,7 @@ package etag import ( "bytes" "io" + "net/http" "net/http/httptest" "testing" @@ -21,7 +22,7 @@ func Test_ETag_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -37,7 +38,7 @@ func Test_ETag_SkipError(t *testing.T) { return fiber.ErrForbidden }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusForbidden, resp.StatusCode) } @@ -53,7 +54,7 @@ func Test_ETag_NotStatusOK(t *testing.T) { return c.SendStatus(fiber.StatusCreated) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusCreated, resp.StatusCode) } @@ -69,7 +70,7 @@ func Test_ETag_NoBody(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) } @@ -102,7 +103,7 @@ func testETagNewEtag(t *testing.T, headerIfNoneMatch, matched bool) { //nolint:r return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) if headerIfNoneMatch { etag := `"non-match"` if matched { @@ -156,7 +157,7 @@ func testETagWeakEtag(t *testing.T, headerIfNoneMatch, matched bool) { //nolint: return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) if headerIfNoneMatch { etag := `W/"non-match"` if matched { @@ -214,7 +215,7 @@ func testETagCustomEtag(t *testing.T, headerIfNoneMatch, matched bool) { //nolin return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) if headerIfNoneMatch { etag := `"non-match"` if matched { @@ -255,7 +256,7 @@ func Test_ETag_CustomEtagPut(t *testing.T) { return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodPut, "/", nil) + req := httptest.NewRequest(fiber.MethodPut, "/", http.NoBody) req.Header.Set(fiber.HeaderIfMatch, `"non-match"`) resp, err := app.Test(req) require.NoError(t, err) diff --git a/middleware/expvar/expvar_test.go b/middleware/expvar/expvar_test.go index a55198255f..e6caa3b82a 100644 --- a/middleware/expvar/expvar_test.go +++ b/middleware/expvar/expvar_test.go @@ -3,6 +3,7 @@ package expvar import ( "bytes" "io" + "net/http" "net/http/httptest" "testing" @@ -20,7 +21,7 @@ func Test_Non_Expvar_Path(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -39,7 +40,7 @@ func Test_Expvar_Index(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMEApplicationJSONCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -60,7 +61,7 @@ func Test_Expvar_Filter(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars?r=cmd", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars?r=cmd", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMEApplicationJSONCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -81,7 +82,7 @@ func Test_Expvar_Other_Path(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars/302", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars/302", http.NoBody)) require.NoError(t, err) require.Equal(t, 302, resp.StatusCode) } @@ -97,7 +98,7 @@ func Test_Expvar_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", http.NoBody)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } diff --git a/middleware/favicon/favicon_test.go b/middleware/favicon/favicon_test.go index 1a40684a5f..5d2c719298 100644 --- a/middleware/favicon/favicon_test.go +++ b/middleware/favicon/favicon_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package favicon import ( @@ -25,19 +24,19 @@ func Test_Middleware_Favicon(t *testing.T) { }) // Skip Favicon middleware - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusNoContent, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(fiber.MethodOptions, "/favicon.ico", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodOptions, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(fiber.MethodPut, "/favicon.ico", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPut, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusMethodNotAllowed, resp.StatusCode, "Status code") require.Equal(t, "GET, HEAD, OPTIONS", resp.Header.Get(fiber.HeaderAllow)) @@ -70,7 +69,7 @@ func Test_Middleware_Favicon_Found(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -90,7 +89,7 @@ func Test_Custom_Favicon_URL(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(http.MethodGet, customURL, nil)) + resp, err := app.Test(httptest.NewRequest(http.MethodGet, customURL, http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") @@ -112,7 +111,7 @@ func Test_Custom_Favicon_Data(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -129,7 +128,7 @@ func Test_Middleware_Favicon_FileSystem(t *testing.T) { FileSystem: os.DirFS("../../.github/testdata"), })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -146,7 +145,7 @@ func Test_Middleware_Favicon_CacheControl(t *testing.T) { File: "../../.github/testdata/favicon.ico", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -182,7 +181,7 @@ func Test_Favicon_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } diff --git a/middleware/filesystem/filesystem_test.go b/middleware/filesystem/filesystem_test.go index 8a2072b2b5..50a8661cad 100644 --- a/middleware/filesystem/filesystem_test.go +++ b/middleware/filesystem/filesystem_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package filesystem import ( @@ -123,7 +122,7 @@ func Test_FileSystem(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tt.url, nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tt.url, http.NoBody)) require.NoError(t, err) require.Equal(t, tt.statusCode, resp.StatusCode) @@ -146,7 +145,7 @@ func Test_FileSystem_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -159,7 +158,7 @@ func Test_FileSystem_Download(t *testing.T) { Download: true, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/img/fiber.png", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/img/fiber.png", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(fiber.HeaderContentLength)) @@ -175,7 +174,7 @@ func Test_FileSystem_NonGetAndHead(t *testing.T) { Root: os.DirFS("../../.github/testdata/fs"), })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/test", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/test", http.NoBody)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } @@ -203,7 +202,7 @@ func Test_FileSystem_NoRoot(t *testing.T) { app := fiber.New() app.Use(New()) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) } @@ -246,7 +245,7 @@ func Test_FileSystem_UsingContentTypeCharset(t *testing.T) { ContentTypeCharset: "UTF-8", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, "text/html; charset=UTF-8", resp.Header.Get("Content-Type")) diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index 409b985a60..f9f749eab4 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -1,6 +1,7 @@ package healthcheck import ( + "net/http" "net/http/httptest" "strconv" "testing" @@ -12,7 +13,7 @@ import ( func shouldGiveStatus(t *testing.T, app *fiber.App, path string, expectedStatus int) { t.Helper() - req, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, nil)) + req, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, http.NoBody)) require.NoError(t, err) require.Equal(t, expectedStatus, req.StatusCode, "path: "+path+" should match "+strconv.Itoa(expectedStatus)) } @@ -144,12 +145,12 @@ func Test_HealthCheck_Custom(t *testing.T) { // Live should return 200 with GET request shouldGiveOK(t, app, "/live") // Live should return 404 with POST request - req, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) + req, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/live", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 404 with POST request - req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", nil)) + req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) diff --git a/middleware/helmet/helmet_test.go b/middleware/helmet/helmet_test.go index c9d4b1c457..b2c8305205 100644 --- a/middleware/helmet/helmet_test.go +++ b/middleware/helmet/helmet_test.go @@ -1,6 +1,7 @@ package helmet import ( + "net/http" "net/http/httptest" "testing" @@ -17,7 +18,7 @@ func Test_Default(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "0", resp.Header.Get(fiber.HeaderXXSSProtection)) require.Equal(t, "nosniff", resp.Header.Get(fiber.HeaderXContentTypeOptions)) @@ -61,7 +62,7 @@ func Test_CustomValues_AllHeaders(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) // Assertions for custom header values require.Equal(t, "0", resp.Header.Get(fiber.HeaderXXSSProtection)) @@ -106,7 +107,7 @@ func Test_RealWorldValues_AllHeaders(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) // Assertions for real-world header values require.Equal(t, "0", resp.Header.Get(fiber.HeaderXXSSProtection)) @@ -141,11 +142,11 @@ func Test_Next(t *testing.T) { return c.SendString("Skipped!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "no-referrer", resp.Header.Get(fiber.HeaderReferrerPolicy)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/next", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/next", http.NoBody)) require.NoError(t, err) require.Equal(t, "", resp.Header.Get(fiber.HeaderReferrerPolicy)) } @@ -161,7 +162,7 @@ func Test_ContentSecurityPolicy(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "default-src 'none'", resp.Header.Get(fiber.HeaderContentSecurityPolicy)) } @@ -178,7 +179,7 @@ func Test_ContentSecurityPolicyReportOnly(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "default-src 'none'", resp.Header.Get(fiber.HeaderContentSecurityPolicyReportOnly)) require.Equal(t, "", resp.Header.Get(fiber.HeaderContentSecurityPolicy)) @@ -195,7 +196,7 @@ func Test_PermissionsPolicy(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, "microphone=()", resp.Header.Get(fiber.HeaderPermissionsPolicy)) } diff --git a/middleware/idempotency/idempotency_test.go b/middleware/idempotency/idempotency_test.go index c70e8fd522..e05f5d0da1 100644 --- a/middleware/idempotency/idempotency_test.go +++ b/middleware/idempotency/idempotency_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package idempotency_test import ( diff --git a/middleware/keyauth/keyauth_test.go b/middleware/keyauth/keyauth_test.go index 2d955ac239..13e2741c33 100644 --- a/middleware/keyauth/keyauth_test.go +++ b/middleware/keyauth/keyauth_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package keyauth import ( @@ -286,7 +285,7 @@ func TestCustomSuccessAndFailureHandlers(t *testing.T) { }) // Create a request without an API key and send it to the app - res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) // Read the response body into a string @@ -298,7 +297,7 @@ func TestCustomSuccessAndFailureHandlers(t *testing.T) { require.Equal(t, "API key is invalid and request was handled by custom error handler", string(body)) // Create a request with a valid API key in the Authorization header - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Add("Authorization", "Bearer "+CorrectKey) // Send the request to the app @@ -335,7 +334,7 @@ func TestCustomNextFunc(t *testing.T) { }) // Create a request with the "/allowed" path and send it to the app - req := httptest.NewRequest(fiber.MethodGet, "/allowed", nil) + req := httptest.NewRequest(fiber.MethodGet, "/allowed", http.NoBody) res, err := app.Test(req) require.NoError(t, err) @@ -348,7 +347,7 @@ func TestCustomNextFunc(t *testing.T) { require.Equal(t, "API key is valid and request was allowed by custom filter", string(body)) // Create a request with a different path and send it to the app without correct key - req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", nil) + req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", http.NoBody) res, err = app.Test(req) require.NoError(t, err) @@ -361,7 +360,7 @@ func TestCustomNextFunc(t *testing.T) { require.Equal(t, string(body), ErrMissingOrMalformedAPIKey.Error()) // Create a request with a different path and send it to the app with correct key - req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", nil) + req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", http.NoBody) req.Header.Add("Authorization", "Basic "+CorrectKey) res, err = app.Test(req) @@ -395,7 +394,7 @@ func TestAuthSchemeToken(t *testing.T) { }) // Create a request with a valid API key in the "Token" Authorization header - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Add("Authorization", "Token "+CorrectKey) // Send the request to the app @@ -431,7 +430,7 @@ func TestAuthSchemeBasic(t *testing.T) { }) // Create a request without an API key and Send the request to the app - res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) // Read the response body into a string @@ -443,7 +442,7 @@ func TestAuthSchemeBasic(t *testing.T) { require.Equal(t, string(body), ErrMissingOrMalformedAPIKey.Error()) // Create a request with a valid API key in the "Authorization" header using the "Basic" scheme - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Add("Authorization", "Basic "+CorrectKey) // Send the request to the app diff --git a/middleware/limiter/limiter_test.go b/middleware/limiter/limiter_test.go index 7b88d1d521..400f98faf0 100644 --- a/middleware/limiter/limiter_test.go +++ b/middleware/limiter/limiter_test.go @@ -2,6 +2,7 @@ package limiter import ( "io" + "net/http" "net/http/httptest" "sync" "testing" @@ -33,7 +34,7 @@ func Test_Limiter_Concurrency_Store(t *testing.T) { var wg sync.WaitGroup singleRequest := func(wg *sync.WaitGroup) { defer wg.Done() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -49,13 +50,13 @@ func Test_Limiter_Concurrency_Store(t *testing.T) { wg.Wait() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -79,7 +80,7 @@ func Test_Limiter_Concurrency(t *testing.T) { var wg sync.WaitGroup singleRequest := func(wg *sync.WaitGroup) { defer wg.Done() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -95,13 +96,13 @@ func Test_Limiter_Concurrency(t *testing.T) { wg.Wait() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -126,21 +127,21 @@ func Test_Limiter_Fixed_Window_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -166,21 +167,21 @@ func Test_Limiter_Fixed_Window_Custom_Storage_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -205,21 +206,21 @@ func Test_Limiter_Sliding_Window_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -245,21 +246,21 @@ func Test_Limiter_Sliding_Window_Custom_Storage_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -283,21 +284,21 @@ func Test_Limiter_Fixed_Window_Skip_Failed_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -322,21 +323,21 @@ func Test_Limiter_Fixed_Window_Custom_Storage_Skip_Failed_Requests(t *testing.T) return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -360,21 +361,21 @@ func Test_Limiter_Sliding_Window_Skip_Failed_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -399,21 +400,21 @@ func Test_Limiter_Sliding_Window_Custom_Storage_Skip_Failed_Requests(t *testing. return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -439,21 +440,21 @@ func Test_Limiter_Fixed_Window_Skip_Successful_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -480,21 +481,21 @@ func Test_Limiter_Fixed_Window_Custom_Storage_Skip_Successful_Requests(t *testin return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -520,21 +521,21 @@ func Test_Limiter_Sliding_Window_Skip_Successful_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -561,21 +562,21 @@ func Test_Limiter_Sliding_Window_Custom_Storage_Skip_Successful_Requests(t *test return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -617,7 +618,7 @@ func Test_Limiter_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -692,7 +693,7 @@ func Test_Sliding_Window(t *testing.T) { }) singleRequest := func(shouldFail bool) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) if shouldFail { require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index 2694e5112d..1faf6acfb6 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package logger import ( @@ -39,7 +38,7 @@ func Test_Logger(t *testing.T) { return errors.New("some random error") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) require.Equal(t, "some random error", buf.String()) @@ -72,21 +71,21 @@ func Test_Logger_locals(t *testing.T) { return c.SendStatus(fiber.StatusOK) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "johndoe", buf.String()) buf.Reset() - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/int", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/int", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "55", buf.String()) buf.Reset() - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/empty", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/empty", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "", buf.String()) @@ -102,7 +101,7 @@ func Test_Logger_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -123,7 +122,7 @@ func Test_Logger_Done(t *testing.T) { return ctx.SendStatus(fiber.StatusOK) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/logging", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/logging", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -138,7 +137,7 @@ func Test_Logger_ErrorTimeZone(t *testing.T) { TimeZone: "invalid", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -160,7 +159,7 @@ func Test_Logger_ErrorOutput_WithoutColor(t *testing.T) { DisableColors: true, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) require.EqualValues(t, 2, *o) @@ -175,7 +174,7 @@ func Test_Logger_ErrorOutput(t *testing.T) { Output: o, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) require.EqualValues(t, 2, *o) @@ -196,7 +195,7 @@ func Test_Logger_All(t *testing.T) { // Alias colors colors := app.Config().ColorScheme - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) @@ -259,7 +258,7 @@ func Test_Logger_WithLatency(t *testing.T) { sleepDuration = 1 * tu.div // Create a new HTTP request to the test route - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int(2*time.Second)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int(2*time.Second)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -301,7 +300,7 @@ func Test_Logger_WithLatency_DefaultFormat(t *testing.T) { sleepDuration = 1 * tu.div // Create a new HTTP request to the test route - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int(2*time.Second)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int(2*time.Second)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -329,7 +328,7 @@ func Test_Query_Params(t *testing.T) { Output: buf, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar&baz=moz", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar&baz=moz", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) @@ -357,7 +356,7 @@ func Test_Response_Body(t *testing.T) { return c.Send([]byte("Post in test")) }) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) expectedGetResponse := "Sample response body" @@ -365,7 +364,7 @@ func Test_Response_Body(t *testing.T) { buf.Reset() // Reset buffer to test POST - _, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/test", nil)) + _, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/test", http.NoBody)) require.NoError(t, err) expectedPostResponse := "Post in test" @@ -389,7 +388,7 @@ func Test_Logger_AppendUint(t *testing.T) { return c.SendString("hello") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "0 5 200", buf.String()) @@ -419,10 +418,10 @@ func Test_Logger_Data_Race(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) go func() { - resp1, err1 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp1, err1 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) wg.Done() }() - resp2, err2 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp2, err2 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) wg.Wait() require.NoError(t, err1) @@ -510,7 +509,7 @@ func Test_Response_Header(t *testing.T) { return c.SendString("Hello fiber!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -531,7 +530,7 @@ func Test_Req_Header(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello fiber!") }) - headerReq := httptest.NewRequest(fiber.MethodGet, "/", nil) + headerReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) headerReq.Header.Add("test", "Hello fiber!") resp, err := app.Test(headerReq) @@ -554,7 +553,7 @@ func Test_ReqHeader_Header(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello fiber!") }) - reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", nil) + reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) reqHeaderReq.Header.Add("test", "Hello fiber!") resp, err := app.Test(reqHeaderReq) @@ -584,7 +583,7 @@ func Test_CustomTags(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello fiber!") }) - reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", nil) + reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) reqHeaderReq.Header.Add("test", "Hello fiber!") resp, err := app.Test(reqHeaderReq) @@ -627,7 +626,7 @@ func Test_Logger_ByteSent_Streaming(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "0 0 200", buf.String()) @@ -649,7 +648,7 @@ func Test_Logger_EnableColors(t *testing.T) { Output: o, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) require.EqualValues(t, 1, *o) diff --git a/middleware/pprof/pprof_test.go b/middleware/pprof/pprof_test.go index 286f031e6e..e5961cdccb 100644 --- a/middleware/pprof/pprof_test.go +++ b/middleware/pprof/pprof_test.go @@ -3,6 +3,7 @@ package pprof import ( "bytes" "io" + "net/http" "net/http/httptest" "testing" @@ -19,7 +20,7 @@ func Test_Non_Pprof_Path(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -37,7 +38,7 @@ func Test_Non_Pprof_Path_WithPrefix(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -55,7 +56,7 @@ func Test_Pprof_Index(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMETextHTMLCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -74,7 +75,7 @@ func Test_Pprof_Index_WithPrefix(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", http.NoBody)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMETextHTMLCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -105,7 +106,7 @@ func Test_Pprof_Subs(t *testing.T) { if sub == "profile" { target += "?seconds=1" } - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, nil), 5000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, http.NoBody), 5000) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) }) @@ -133,7 +134,7 @@ func Test_Pprof_Subs_WithPrefix(t *testing.T) { if sub == "profile" { target += "?seconds=1" } - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, nil), 5000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, http.NoBody), 5000) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) }) @@ -149,7 +150,7 @@ func Test_Pprof_Other(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/302", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/302", http.NoBody)) require.NoError(t, err) require.Equal(t, 302, resp.StatusCode) } @@ -163,7 +164,7 @@ func Test_Pprof_Other_WithPrefix(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/302", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/302", http.NoBody)) require.NoError(t, err) require.Equal(t, 302, resp.StatusCode) } @@ -178,7 +179,7 @@ func Test_Pprof_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", http.NoBody)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } @@ -194,7 +195,7 @@ func Test_Pprof_Next_WithPrefix(t *testing.T) { Prefix: "/federated-fiber", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", http.NoBody)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } diff --git a/middleware/proxy/proxy_test.go b/middleware/proxy/proxy_test.go index 408ee71a5f..340d9ee2b0 100644 --- a/middleware/proxy/proxy_test.go +++ b/middleware/proxy/proxy_test.go @@ -5,6 +5,7 @@ import ( "errors" "io" "net" + "net/http" "net/http/httptest" "strings" "testing" @@ -76,7 +77,7 @@ func Test_Proxy_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -89,7 +90,7 @@ func Test_Proxy(t *testing.T) { return c.SendStatus(fiber.StatusTeapot) }) - resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) + resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) @@ -97,7 +98,7 @@ func Test_Proxy(t *testing.T) { app.Use(Balancer(Config{Servers: []string{addr}})) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Host = addr resp, err = app.Test(req) require.NoError(t, err) @@ -194,7 +195,7 @@ func Test_Proxy_Forward(t *testing.T) { app.Use(Forward("http://" + addr)) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -258,7 +259,7 @@ func Test_Proxy_Modify_Response(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -285,7 +286,7 @@ func Test_Proxy_Modify_Request(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -309,7 +310,7 @@ func Test_Proxy_Timeout_Slow_Server(t *testing.T) { Timeout: 600 * time.Millisecond, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -333,7 +334,7 @@ func Test_Proxy_With_Timeout(t *testing.T) { Timeout: 100 * time.Millisecond, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) @@ -355,7 +356,7 @@ func Test_Proxy_Buffer_Size_Response(t *testing.T) { app := fiber.New() app.Use(Balancer(Config{Servers: []string{addr}})) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) @@ -365,7 +366,7 @@ func Test_Proxy_Buffer_Size_Response(t *testing.T) { ReadBufferSize: 1024 * 8, })) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) } @@ -381,7 +382,7 @@ func Test_Proxy_Do_RestoreOriginalURL(t *testing.T) { app.Get("/test", func(c fiber.Ctx) error { return Do(c, "http://"+addr) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) require.NoError(t, err1) require.Equal(t, "/test", resp.Request.URL.String()) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -398,7 +399,7 @@ func Test_Proxy_Do_WithRealURL(t *testing.T) { return Do(c, "https://www.google.com") }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) require.NoError(t, err1) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "/test", resp.Request.URL.String()) @@ -415,7 +416,7 @@ func Test_Proxy_Do_WithRedirect(t *testing.T) { return Do(c, "https://google.com") }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), 1500) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), 1500) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -431,7 +432,7 @@ func Test_Proxy_DoRedirects_RestoreOriginalURL(t *testing.T) { return DoRedirects(c, "http://google.com", 1) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), 1500) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), 1500) require.NoError(t, err1) _, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -447,7 +448,7 @@ func Test_Proxy_DoRedirects_TooManyRedirects(t *testing.T) { return DoRedirects(c, "http://google.com", 0) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), 1500) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), 1500) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -469,7 +470,7 @@ func Test_Proxy_DoTimeout_RestoreOriginalURL(t *testing.T) { return DoTimeout(c, "http://"+addr, time.Second) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -492,7 +493,7 @@ func Test_Proxy_DoTimeout_Timeout(t *testing.T) { return DoTimeout(c, "http://"+addr, time.Second) }) - _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int((1*time.Second)/time.Millisecond)) + _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int((1*time.Second)/time.Millisecond)) require.Equal(t, errors.New("test: timeout error 1000ms"), err1) } @@ -509,7 +510,7 @@ func Test_Proxy_DoDeadline_RestoreOriginalURL(t *testing.T) { return DoDeadline(c, "http://"+addr, time.Now().Add(time.Second)) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -532,7 +533,7 @@ func Test_Proxy_DoDeadline_PastDeadline(t *testing.T) { return DoDeadline(c, "http://"+addr, time.Now().Add(time.Second)) }) - _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int((1*time.Second)/time.Millisecond)) + _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int((1*time.Second)/time.Millisecond)) require.Equal(t, errors.New("test: timeout error 1000ms"), err1) } @@ -557,7 +558,7 @@ func Test_Proxy_Do_HTTP_Prefix_URL(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/http://"+addr, nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/http://"+addr, http.NoBody)) require.NoError(t, err) s, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -629,7 +630,7 @@ func Test_ProxyBalancer_Custom_Client(t *testing.T) { return c.SendStatus(fiber.StatusTeapot) }) - resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) + resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) @@ -646,7 +647,7 @@ func Test_ProxyBalancer_Custom_Client(t *testing.T) { Timeout: time.Second, }})) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Host = addr resp, err = app.Test(req) require.NoError(t, err) @@ -700,7 +701,7 @@ func Test_Proxy_Balancer_Forward_Local(t *testing.T) { app.Use(BalancerForward([]string{addr})) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) diff --git a/middleware/recover/recover_test.go b/middleware/recover/recover_test.go index 9b5962db90..d28a0399bc 100644 --- a/middleware/recover/recover_test.go +++ b/middleware/recover/recover_test.go @@ -1,6 +1,7 @@ package recover //nolint:predeclared // TODO: Rename to some non-builtin import ( + "net/http" "net/http/httptest" "testing" @@ -24,7 +25,7 @@ func Test_Recover(t *testing.T) { panic("Hi, I'm an error!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) } @@ -39,7 +40,7 @@ func Test_Recover_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -55,7 +56,7 @@ func Test_Recover_EnableStackTrace(t *testing.T) { panic("Hi, I'm an error!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) } diff --git a/middleware/redirect/redirect_test.go b/middleware/redirect/redirect_test.go index ac02c1b46f..612454b8b3 100644 --- a/middleware/redirect/redirect_test.go +++ b/middleware/redirect/redirect_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package redirect import ( diff --git a/middleware/requestid/requestid_test.go b/middleware/requestid/requestid_test.go index c739407be0..93facc5138 100644 --- a/middleware/requestid/requestid_test.go +++ b/middleware/requestid/requestid_test.go @@ -1,6 +1,7 @@ package requestid import ( + "net/http" "net/http/httptest" "testing" @@ -19,14 +20,14 @@ func Test_RequestID(t *testing.T) { return c.SendString("Hello, World 👋!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) reqid := resp.Header.Get(fiber.HeaderXRequestID) require.Len(t, reqid, 36) - req := httptest.NewRequest(fiber.MethodGet, "/", nil) + req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) req.Header.Add(fiber.HeaderXRequestID, reqid) resp, err = app.Test(req) @@ -45,7 +46,7 @@ func Test_RequestID_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Empty(t, resp.Header.Get(fiber.HeaderXRequestID)) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) @@ -70,7 +71,7 @@ func Test_RequestID_FromContext(t *testing.T) { return c.Next() }) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, reqID, ctxVal) } diff --git a/middleware/rewrite/rewrite_test.go b/middleware/rewrite/rewrite_test.go index bedbbcfa47..4cd1c4d00b 100644 --- a/middleware/rewrite/rewrite_test.go +++ b/middleware/rewrite/rewrite_test.go @@ -1,4 +1,3 @@ -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package rewrite import ( diff --git a/middleware/skip/skip_test.go b/middleware/skip/skip_test.go index cfa95f8cbc..6e76afab84 100644 --- a/middleware/skip/skip_test.go +++ b/middleware/skip/skip_test.go @@ -1,6 +1,7 @@ package skip_test import ( + "net/http" "net/http/httptest" "testing" @@ -17,7 +18,7 @@ func Test_Skip(t *testing.T) { app.Use(skip.New(errTeapotHandler, func(fiber.Ctx) bool { return true })) app.Get("/", helloWorldHandler) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) } @@ -30,7 +31,7 @@ func Test_SkipFalse(t *testing.T) { app.Use(skip.New(errTeapotHandler, func(fiber.Ctx) bool { return false })) app.Get("/", helloWorldHandler) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) } @@ -43,7 +44,7 @@ func Test_SkipNilFunc(t *testing.T) { app.Use(skip.New(errTeapotHandler, nil)) app.Get("/", helloWorldHandler) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) } diff --git a/middleware/timeout/timeout_test.go b/middleware/timeout/timeout_test.go index b08445eb2a..7b408b425c 100644 --- a/middleware/timeout/timeout_test.go +++ b/middleware/timeout/timeout_test.go @@ -4,6 +4,7 @@ import ( "context" "errors" "fmt" + "net/http" "net/http/httptest" "testing" "time" @@ -27,12 +28,12 @@ func Test_WithContextTimeout(t *testing.T) { }, 100*time.Millisecond) app.Get("/test/:sleepTime", h) testTimeout := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode, "Status code") } testSucces := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") } @@ -59,12 +60,12 @@ func Test_WithContextTimeoutWithCustomError(t *testing.T) { }, 100*time.Millisecond, ErrFooTimeOut) app.Get("/test/:sleepTime", h) testTimeout := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode, "Status code") } testSucces := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") } diff --git a/mount_test.go b/mount_test.go index 1ec62c0ef6..540cedb207 100644 --- a/mount_test.go +++ b/mount_test.go @@ -2,7 +2,6 @@ // 🤖 Github Repository: https://github.com/gofiber/fiber // 📌 API Documentation: https://docs.gofiber.io -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package fiber import ( @@ -458,14 +457,14 @@ func Test_Mount_Route_Names(t *testing.T) { require.Equal(t, "/app2/users", route.Path) // GetRouteURL inside handler - req := httptest.NewRequest(MethodGet, "/app1/users", nil) + req := httptest.NewRequest(MethodGet, "/app1/users", http.NoBody) resp, err := rootApp.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // ctx.App().GetRoute() inside handler - req = httptest.NewRequest(MethodPost, "/app1/users", nil) + req = httptest.NewRequest(MethodPost, "/app1/users", http.NoBody) resp, err = rootApp.Test(req) require.NoError(t, err, "app.Test(req)") diff --git a/router_test.go b/router_test.go index c25a317e32..cc46c492b1 100644 --- a/router_test.go +++ b/router_test.go @@ -2,7 +2,6 @@ // 📃 Github Repository: https://github.com/gofiber/fiber // 📌 API Documentation: https://docs.gofiber.io -//nolint:bodyclose // Much easier to just ignore memory leaks in tests package fiber import ( @@ -10,6 +9,7 @@ import ( "errors" "fmt" "io" + "net/http" "net/http/httptest" "os" "testing" @@ -40,7 +40,7 @@ func Test_Route_Match_SameLength(t *testing.T) { return c.SendString(c.Params("param")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/:param", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/:param", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -49,7 +49,7 @@ func Test_Route_Match_SameLength(t *testing.T) { require.Equal(t, ":param", app.getString(body)) // with param - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -67,7 +67,7 @@ func Test_Route_Match_Star(t *testing.T) { return c.SendString(c.Params("*")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/*", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/*", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -76,7 +76,7 @@ func Test_Route_Match_Star(t *testing.T) { require.Equal(t, "*", app.getString(body)) // with param - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -115,7 +115,7 @@ func Test_Route_Match_Root(t *testing.T) { return c.SendString("root") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -135,7 +135,7 @@ func Test_Route_Match_Parser(t *testing.T) { app.Get("/Foobar/*", func(c Ctx) error { return c.SendString(c.Params("*")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -144,7 +144,7 @@ func Test_Route_Match_Parser(t *testing.T) { require.Equal(t, "bar", app.getString(body)) // with star - resp, err = app.Test(httptest.NewRequest(MethodGet, "/Foobar/test", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/Foobar/test", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -162,7 +162,7 @@ func Test_Route_Match_Middleware(t *testing.T) { return c.SendString(c.Params("*")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/*", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/*", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -171,7 +171,7 @@ func Test_Route_Match_Middleware(t *testing.T) { require.Equal(t, "*", app.getString(body)) // with param - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/bar/fasel", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/bar/fasel", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -189,7 +189,7 @@ func Test_Route_Match_UnescapedPath(t *testing.T) { return c.SendString("test") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -197,13 +197,13 @@ func Test_Route_Match_UnescapedPath(t *testing.T) { require.NoError(t, err, "app.Test(req)") require.Equal(t, "test", app.getString(body)) // without special chars - resp, err = app.Test(httptest.NewRequest(MethodGet, "/créer", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/créer", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // check deactivated behavior app.config.UnescapePath = false - resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") } @@ -227,7 +227,7 @@ func Test_Route_Match_WithEscapeChar(t *testing.T) { }) // check static route - resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/some/resource/name:customVerb", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/some/resource/name:customVerb", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -236,7 +236,7 @@ func Test_Route_Match_WithEscapeChar(t *testing.T) { require.Equal(t, "static", app.getString(body)) // check group route - resp, err = app.Test(httptest.NewRequest(MethodGet, "/v2/:firstVerb/:customVerb", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/v2/:firstVerb/:customVerb", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -245,7 +245,7 @@ func Test_Route_Match_WithEscapeChar(t *testing.T) { require.Equal(t, "group", app.getString(body)) // check param route - resp, err = app.Test(httptest.NewRequest(MethodGet, "/v3/awesome/name:customVerb", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/v3/awesome/name:customVerb", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -263,7 +263,7 @@ func Test_Route_Match_Middleware_HasPrefix(t *testing.T) { return c.SendString("middleware") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -281,7 +281,7 @@ func Test_Route_Match_Middleware_Root(t *testing.T) { return c.SendString("middleware") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/everything", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/everything", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -342,11 +342,11 @@ func Test_Route_Static_Root(t *testing.T) { Browse: true, }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -357,11 +357,11 @@ func Test_Route_Static_Root(t *testing.T) { app = New() app.Static("/", dir) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -379,15 +379,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { Browse: true, }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/static", nil)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -400,15 +400,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { Browse: true, }) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -419,15 +419,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { app = New() app.Static("/static", dir) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -438,15 +438,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { app = New() app.Static("/static/", dir) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") From 7661fbb3e318de2f0e63117b1c57a67b63c1345e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Wed, 28 Feb 2024 13:46:06 +0100 Subject: [PATCH 49/51] revert(tests): undo http.NoBody usage --- app_test.go | 176 +++++++++--------- bind_test.go | 9 +- ctx_test.go | 67 ++++--- middleware/adaptor/adaptor_test.go | 6 +- middleware/basicauth/basicauth_test.go | 5 +- middleware/cache/cache_test.go | 109 ++++++----- middleware/compress/compress_test.go | 15 +- middleware/cors/cors_test.go | 3 +- middleware/csrf/csrf_test.go | 11 +- middleware/earlydata/earlydata_test.go | 9 +- .../encryptcookie/encryptcookie_test.go | 3 +- middleware/etag/etag_test.go | 17 +- middleware/expvar/expvar_test.go | 11 +- middleware/favicon/favicon_test.go | 20 +- middleware/filesystem/filesystem_test.go | 12 +- middleware/healthcheck/healthcheck_test.go | 7 +- middleware/helmet/helmet_test.go | 17 +- middleware/idempotency/idempotency_test.go | 3 +- middleware/keyauth/keyauth_test.go | 16 +- middleware/limiter/limiter_test.go | 113 ++++++----- middleware/logger/logger_test.go | 48 ++--- middleware/pprof/pprof_test.go | 21 +-- middleware/proxy/proxy_test.go | 47 +++-- middleware/recover/recover_test.go | 7 +- middleware/requestid/requestid_test.go | 9 +- middleware/skip/skip_test.go | 7 +- middleware/timeout/timeout_test.go | 9 +- mount_test.go | 45 +++-- router_test.go | 67 ++++--- 29 files changed, 433 insertions(+), 456 deletions(-) diff --git a/app_test.go b/app_test.go index 3b505049ba..58c05932b2 100644 --- a/app_test.go +++ b/app_test.go @@ -37,7 +37,7 @@ func testEmptyHandler(_ Ctx) error { func testStatus200(t *testing.T, app *App, url, method string) { t.Helper() - req := httptest.NewRequest(method, url, http.NoBody) + req := httptest.NewRequest(method, url, nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -67,41 +67,41 @@ func Test_App_MethodNotAllowed(t *testing.T) { app.Options("/", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest(MethodPost, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, "", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "POST, OPTIONS", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", nil)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "POST, OPTIONS", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodPut, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodPut, "/", nil)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "POST, OPTIONS", resp.Header.Get(HeaderAllow)) app.Get("/", testEmptyHandler) - resp, err = app.Test(httptest.NewRequest(MethodTrace, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodTrace, "/", nil)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "GET, POST, OPTIONS", resp.Header.Get(HeaderAllow)) - resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodPatch, "/", nil)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "GET, POST, OPTIONS", resp.Header.Get(HeaderAllow)) app.Head("/", testEmptyHandler) - resp, err = app.Test(httptest.NewRequest(MethodPut, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodPut, "/", nil)) require.NoError(t, err) require.Equal(t, 405, resp.StatusCode) require.Equal(t, "GET, HEAD, POST, OPTIONS", resp.Header.Get(HeaderAllow)) @@ -117,7 +117,7 @@ func Test_App_Custom_Middleware_404_Should_Not_SetMethodNotAllowed(t *testing.T) app.Post("/", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) @@ -127,7 +127,7 @@ func Test_App_Custom_Middleware_404_Should_Not_SetMethodNotAllowed(t *testing.T) g.Post("/", testEmptyHandler) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/with-next", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/with-next", nil)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } @@ -143,7 +143,7 @@ func Test_App_ServerErrorHandler_SmallReadBuffer(t *testing.T) { panic(errors.New("should never called")) }) - request := httptest.NewRequest(MethodGet, "/", http.NoBody) + request := httptest.NewRequest(MethodGet, "/", nil) logHeaderSlice := make([]string, 5000) request.Header.Set("Very-Long-Header", strings.Join(logHeaderSlice, "-")) _, err := app.Test(request) @@ -164,7 +164,7 @@ func Test_App_Errors(t *testing.T) { return errors.New("hi, i'm an error") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 500, resp.StatusCode, "Status code") @@ -212,23 +212,23 @@ func Test_App_CustomConstraint(t *testing.T) { return c.SendString("test") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/test2", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/test2", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/c", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/c", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/cc", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/cc", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/cc", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/cc", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") } @@ -245,7 +245,7 @@ func Test_App_ErrorHandler_Custom(t *testing.T) { return errors.New("hi, i'm an error") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -275,7 +275,7 @@ func Test_App_ErrorHandler_HandlerStack(t *testing.T) { return errors.New("0: GET error") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 500, resp.StatusCode, "Status code") @@ -301,7 +301,7 @@ func Test_App_ErrorHandler_RouteStack(t *testing.T) { return errors.New("0: GET error") // [1] return to USE }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 500, resp.StatusCode, "Status code") @@ -352,7 +352,7 @@ func Test_App_Nested_Params(t *testing.T) { return c.Status(200).Send([]byte("Good job")) }) - req := httptest.NewRequest(MethodGet, "/test/john/test/doe", http.NoBody) + req := httptest.NewRequest(MethodGet, "/test/john/test/doe", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -379,15 +379,15 @@ func Test_App_Use_Params(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/john/doe", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/john/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -416,7 +416,7 @@ func Test_App_Use_UnescapedPath(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/cR%C3%A9eR/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/cR%C3%A9eR/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -426,7 +426,7 @@ func Test_App_Use_UnescapedPath(t *testing.T) { require.Equal(t, "اختبار", app.getString(body)) // with lowercase letters - resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") } @@ -440,19 +440,19 @@ func Test_App_Use_CaseSensitive(t *testing.T) { }) // wrong letters in the requested route -> 404 - resp, err := app.Test(httptest.NewRequest(MethodGet, "/AbC", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/AbC", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") // right letters in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // check the detected path when the case insensitive recognition is activated app.config.CaseSensitive = false // check the case sensitive feature - resp, err = app.Test(httptest.NewRequest(MethodGet, "/AbC", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/AbC", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -476,22 +476,22 @@ func Test_App_Not_Use_StrictRouting(t *testing.T) { }) // wrong path in the requested route -> 404 - resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // right path in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // wrong path with group in the requested route -> 404 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // right path with group in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -509,7 +509,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { return c.SendString(c.Path()) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/john", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/john", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -517,7 +517,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { require.NoError(t, err) require.Equal(t, "/john", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -525,7 +525,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { require.NoError(t, err) require.Equal(t, "/doe", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/john", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/john", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -533,7 +533,7 @@ func Test_App_Use_MultiplePrefix(t *testing.T) { require.NoError(t, err) require.Equal(t, "/test/john", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/doe", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -556,22 +556,22 @@ func Test_App_Use_StrictRouting(t *testing.T) { }) // wrong path in the requested route -> 404 - resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/abc/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") // right path in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/abc", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // wrong path with group in the requested route -> 404 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") // right path with group in the requrested route -> 200 - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -591,15 +591,15 @@ func Test_App_Add_Method_Test(t *testing.T) { app.Add([]string{"JOHN"}, "/doe", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest("JOHN", "/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest("JOHN", "/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusMethodNotAllowed, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest("UNKNOWN", "/doe", http.NoBody)) + resp, err = app.Test(httptest.NewRequest("UNKNOWN", "/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotImplemented, resp.StatusCode, "Status code") @@ -617,7 +617,7 @@ func Test_App_GETOnly(t *testing.T) { return c.SendString("Hello 👋!") }) - req := httptest.NewRequest(MethodPost, "/", http.NoBody) + req := httptest.NewRequest(MethodPost, "/", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusMethodNotAllowed, resp.StatusCode, "Status code") @@ -637,7 +637,7 @@ func Test_App_Use_Params_Group(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john/doe/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/prefix/john/doe/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") } @@ -654,7 +654,7 @@ func Test_App_Chaining(t *testing.T) { // check handler count for registered HEAD route require.Len(t, app.stack[app.methodInt(MethodHead)][0].Handlers, 5, "app.Test(req)") - req := httptest.NewRequest(MethodPost, "/john", http.NoBody) + req := httptest.NewRequest(MethodPost, "/john", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -664,7 +664,7 @@ func Test_App_Chaining(t *testing.T) { return c.SendStatus(203) }) - req = httptest.NewRequest(MethodGet, "/test", http.NoBody) + req = httptest.NewRequest(MethodGet, "/test", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -696,7 +696,7 @@ func Test_App_Order(t *testing.T) { return nil }) - req := httptest.NewRequest(MethodGet, "/test", http.NoBody) + req := httptest.NewRequest(MethodGet, "/test", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") @@ -909,7 +909,7 @@ func Test_App_Static_Index_Default(t *testing.T) { app.Static("", "./.github/") app.Static("test", "", Static{Index: "index.html"}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -919,7 +919,7 @@ func Test_App_Static_Index_Default(t *testing.T) { require.NoError(t, err) require.Contains(t, string(body), "Hello, World!") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/not-found", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/not-found", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -936,7 +936,7 @@ func Test_App_Static_Direct(t *testing.T) { app.Static("/", "./.github") - resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -946,7 +946,7 @@ func Test_App_Static_Direct(t *testing.T) { require.NoError(t, err) require.Contains(t, string(body), "Hello, World!") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/testdata/testRoutes.json", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/testdata/testRoutes.json", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -964,7 +964,7 @@ func Test_App_Static_MaxAge(t *testing.T) { app.Static("/", "./.github", Static{MaxAge: 100}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -983,11 +983,11 @@ func Test_App_Static_Custom_CacheControl(t *testing.T) { return nil }}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/index.html", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, "no-cache, no-store, must-revalidate", resp.Header.Get(HeaderCacheControl), "CacheControl Control") - normalResp, normalErr := app.Test(httptest.NewRequest(MethodGet, "/config.yml", http.NoBody)) + normalResp, normalErr := app.Test(httptest.NewRequest(MethodGet, "/config.yml", nil)) require.NoError(t, normalErr, "app.Test(req)") require.Equal(t, "", normalResp.Header.Get(HeaderCacheControl), "CacheControl Control") } @@ -998,7 +998,7 @@ func Test_App_Static_Download(t *testing.T) { app.Static("/fiber.png", "./.github/testdata/fs/img/fiber.png", Static{Download: true}) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/fiber.png", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/fiber.png", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -1017,7 +1017,7 @@ func Test_App_Static_Group(t *testing.T) { grp.Static("/v2", "./.github/index.html") - req := httptest.NewRequest(MethodGet, "/v1/v2", http.NoBody) + req := httptest.NewRequest(MethodGet, "/v1/v2", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1028,7 +1028,7 @@ func Test_App_Static_Group(t *testing.T) { grp = app.Group("/v2") grp.Static("/v3*", "./.github/index.html") - req = httptest.NewRequest(MethodGet, "/v2/v3/john/doe", http.NoBody) + req = httptest.NewRequest(MethodGet, "/v2/v3/john/doe", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1041,7 +1041,7 @@ func Test_App_Static_Wildcard(t *testing.T) { app.Static("*", "./.github/index.html") - req := httptest.NewRequest(MethodGet, "/yesyes/john/doe", http.NoBody) + req := httptest.NewRequest(MethodGet, "/yesyes/john/doe", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1058,7 +1058,7 @@ func Test_App_Static_Prefix_Wildcard(t *testing.T) { app.Static("/test/*", "./.github/index.html") - req := httptest.NewRequest(MethodGet, "/test/john/doe", http.NoBody) + req := httptest.NewRequest(MethodGet, "/test/john/doe", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1067,7 +1067,7 @@ func Test_App_Static_Prefix_Wildcard(t *testing.T) { app.Static("/my/nameisjohn*", "./.github/index.html") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/my/nameisjohn/no/its/not", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/my/nameisjohn/no/its/not", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) @@ -1082,7 +1082,7 @@ func Test_App_Static_Prefix(t *testing.T) { app := New() app.Static("/john", "./.github") - req := httptest.NewRequest(MethodGet, "/john/index.html", http.NoBody) + req := httptest.NewRequest(MethodGet, "/john/index.html", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1091,7 +1091,7 @@ func Test_App_Static_Prefix(t *testing.T) { app.Static("/prefix", "./.github/testdata") - req = httptest.NewRequest(MethodGet, "/prefix/index.html", http.NoBody) + req = httptest.NewRequest(MethodGet, "/prefix/index.html", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1100,7 +1100,7 @@ func Test_App_Static_Prefix(t *testing.T) { app.Static("/single", "./.github/testdata/testRoutes.json") - req = httptest.NewRequest(MethodGet, "/single", http.NoBody) + req = httptest.NewRequest(MethodGet, "/single", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1112,7 +1112,7 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app := New() app.Static("/john", "./.github") - req := httptest.NewRequest(MethodGet, "/john/", http.NoBody) + req := httptest.NewRequest(MethodGet, "/john/", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1121,7 +1121,7 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app.Static("/john_without_index", "./.github/testdata/fs/css") - req = httptest.NewRequest(MethodGet, "/john_without_index/", http.NoBody) + req = httptest.NewRequest(MethodGet, "/john_without_index/", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") @@ -1130,14 +1130,14 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app.Static("/john/", "./.github") - req = httptest.NewRequest(MethodGet, "/john/", http.NoBody) + req = httptest.NewRequest(MethodGet, "/john/", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(HeaderContentLength)) require.Equal(t, MIMETextHTMLCharsetUTF8, resp.Header.Get(HeaderContentType)) - req = httptest.NewRequest(MethodGet, "/john", http.NoBody) + req = httptest.NewRequest(MethodGet, "/john", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1146,7 +1146,7 @@ func Test_App_Static_Trailing_Slash(t *testing.T) { app.Static("/john_without_index/", "./.github/testdata/fs/css") - req = httptest.NewRequest(MethodGet, "/john_without_index/", http.NoBody) + req = httptest.NewRequest(MethodGet, "/john_without_index/", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") @@ -1168,7 +1168,7 @@ func Test_App_Static_Next(t *testing.T) { }) t.Run("app.Static is skipped: invoking Get handler", func(t *testing.T) { - req := httptest.NewRequest(MethodGet, "/", http.NoBody) + req := httptest.NewRequest(MethodGet, "/", nil) req.Header.Set("X-Custom-Header", "skip") resp, err := app.Test(req) require.NoError(t, err) @@ -1182,7 +1182,7 @@ func Test_App_Static_Next(t *testing.T) { }) t.Run("app.Static is not skipped: serving index.html", func(t *testing.T) { - req := httptest.NewRequest(MethodGet, "/", http.NoBody) + req := httptest.NewRequest(MethodGet, "/", nil) req.Header.Set("X-Custom-Header", "don't skip") resp, err := app.Test(req) require.NoError(t, err) @@ -1213,7 +1213,7 @@ func Test_App_Mixed_Routes_WithSameLen(t *testing.T) { }) // match get route - req := httptest.NewRequest(MethodGet, "/foobar", http.NoBody) + req := httptest.NewRequest(MethodGet, "/foobar", nil) resp, err := app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1226,7 +1226,7 @@ func Test_App_Mixed_Routes_WithSameLen(t *testing.T) { require.Equal(t, "FOO_BAR", string(body)) // match static route - req = httptest.NewRequest(MethodGet, "/tesbar", http.NoBody) + req = httptest.NewRequest(MethodGet, "/tesbar", nil) resp, err = app.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1299,13 +1299,13 @@ func Test_App_Group(t *testing.T) { api := grp.Group("/v1") api.Post("/", dummyHandler) - resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") // require.Equal(t, "/test/v1", resp.Header.Get("Location"), "Location") api.Get("/users", dummyHandler) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") // require.Equal(t, "/test/v1/users", resp.Header.Get("Location"), "Location") @@ -1340,21 +1340,21 @@ func Test_App_Route(t *testing.T) { register.Route("/v1").Get(dummyHandler).Post(dummyHandler) - resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") register.Route("/v1").Route("/v2").Route("/v3").Get(dummyHandler).Trace(dummyHandler) - resp, err = app.Test(httptest.NewRequest(MethodTrace, "/test/v1/v2/v3", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodTrace, "/test/v1/v2/v3", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/v2/v3", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/v2/v3", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") } @@ -1391,7 +1391,7 @@ func Test_App_Next_Method(t *testing.T) { return err }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") } @@ -1428,7 +1428,7 @@ func Test_Test_Timeout(t *testing.T) { app.Get("/", testEmptyHandler) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody), -1) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil), -1) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -1437,7 +1437,7 @@ func Test_Test_Timeout(t *testing.T) { return nil }) - _, err = app.Test(httptest.NewRequest(MethodGet, "/timeout", http.NoBody), 20) + _, err = app.Test(httptest.NewRequest(MethodGet, "/timeout", nil), 20) require.Error(t, err, "app.Test(req)") } @@ -1611,7 +1611,7 @@ func Test_App_SmallReadBuffer(t *testing.T) { go func() { time.Sleep(500 * time.Millisecond) - req, err := http.NewRequestWithContext(context.Background(), MethodGet, "http://127.0.0.1:4006/small-read-buffer", http.NoBody) + req, err := http.NewRequestWithContext(context.Background(), MethodGet, "http://127.0.0.1:4006/small-read-buffer", nil) require.NoError(t, err) var client http.Client resp, err := client.Do(req) @@ -1637,7 +1637,7 @@ func Test_App_Error_In_Fasthttp_Server(t *testing.T) { } app.server.GetOnly = true - resp, err := app.Test(httptest.NewRequest(MethodPost, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodPost, "/", nil)) require.NoError(t, err) require.Equal(t, 500, resp.StatusCode) } @@ -1648,13 +1648,13 @@ func Test_App_New_Test_Parallel(t *testing.T) { t.Run("Test_App_New_Test_Parallel_1", func(t *testing.T) { t.Parallel() app := New(Config{Immutable: true}) - _, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err) }) t.Run("Test_App_New_Test_Parallel_2", func(t *testing.T) { t.Parallel() app := New(Config{Immutable: true}) - _, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err) }) } @@ -1735,7 +1735,7 @@ func Test_App_Test_no_timeout_infinitely(t *testing.T) { return nil }) - req := httptest.NewRequest(MethodGet, "/", http.NoBody) + req := httptest.NewRequest(MethodGet, "/", nil) _, err = app.Test(req, -1) }() diff --git a/bind_test.go b/bind_test.go index 59186abab5..436c2e4bc9 100644 --- a/bind_test.go +++ b/bind_test.go @@ -7,7 +7,6 @@ import ( "encoding/json" "errors" "fmt" - "net/http" "net/http/httptest" "reflect" "testing" @@ -1100,9 +1099,9 @@ func Test_Bind_URI(t *testing.T) { require.Equal(t, uint(222), d.RoleID) return nil }) - _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", http.NoBody)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", http.NoBody)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil)) require.NoError(t, err) } @@ -1121,9 +1120,9 @@ func Test_Bind_URI_Map(t *testing.T) { require.Equal(t, uint(222), d["roleId"]) return nil }) - _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", http.NoBody)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", http.NoBody)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil)) require.NoError(t, err) } diff --git a/ctx_test.go b/ctx_test.go index 3a266a9491..fb601bf49b 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -17,7 +17,6 @@ import ( "io" "mime/multipart" "net" - "net/http" "net/http/httptest" "os" "path/filepath" @@ -856,7 +855,7 @@ func Test_Ctx_UserContext_Multiple_Requests(t *testing.T) { i := i t.Run(fmt.Sprintf("request_%d", i), func(t *testing.T) { t.Parallel() - resp, err := app.Test(httptest.NewRequest(MethodGet, fmt.Sprintf("/?input=%d", i), http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, fmt.Sprintf("/?input=%d", i), nil)) require.NoError(t, err, "Unexpected error from response") require.Equal(t, StatusOK, resp.StatusCode, "context.Context returned from c.UserContext() is reused") @@ -1740,7 +1739,7 @@ func Test_Ctx_PortInHandler(t *testing.T) { return c.SendString(c.Port()) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/port", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/port", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -2077,7 +2076,7 @@ func Test_Ctx_Locals(t *testing.T) { require.Equal(t, "doe", c.Locals("john")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2099,7 +2098,7 @@ func Test_Ctx_Locals_Generic(t *testing.T) { require.Equal(t, 0, Locals[int](c, "isHuman")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2122,7 +2121,7 @@ func Test_Ctx_Locals_GenericCustomStruct(t *testing.T) { require.Equal(t, User{"john", 18}, Locals[User](c, "user")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2173,7 +2172,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { }) // Test without TLS handler - resp, err := app.Test(httptest.NewRequest(MethodGet, "/ServerName", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/ServerName", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -2191,7 +2190,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { }} // Test ServerName - resp, err = app.Test(httptest.NewRequest(MethodGet, "/ServerName", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/ServerName", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) @@ -2199,7 +2198,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { require.Equal(t, []byte("example.golang"), body) // Test SignatureSchemes - resp, err = app.Test(httptest.NewRequest(MethodGet, "/SignatureSchemes", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/SignatureSchemes", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) @@ -2207,7 +2206,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { require.Equal(t, "["+strconv.Itoa(pssWithSHA256)+"]", string(body)) // Test SupportedVersions - resp, err = app.Test(httptest.NewRequest(MethodGet, "/SupportedVersions", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/SupportedVersions", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) @@ -2322,23 +2321,23 @@ func Test_Ctx_Params(t *testing.T) { require.Equal(t, "first", c.Params("Id")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/im/a/cookie", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/im/a/cookie", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/1111/blafasel/2222", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test3/1111/blafasel/2222", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test4", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test4", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test5/first/second", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test5/first/second", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2356,11 +2355,11 @@ func Test_Ctx_Params_Case_Sensitive(t *testing.T) { require.Equal(t, "second", c.Params("Id")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test/john", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/first/second", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test2/first/second", nil)) require.NoError(t, err) require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -2409,7 +2408,7 @@ func Test_Ctx_Path(t *testing.T) { require.Equal(t, "/اختبار/", c.Path("/%D8%A7%D8%AE%D8%AA%D8%A8%D8%A7%D8%B1/")) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/specialChars/cr%C3%A9er", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/specialChars/cr%C3%A9er", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -3128,7 +3127,7 @@ func Test_Ctx_Route(t *testing.T) { require.Equal(t, "/test", c.Route().Path) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -3147,7 +3146,7 @@ func Test_Ctx_RouteNormalized(t *testing.T) { require.Equal(t, "/test", c.Route().Path) return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "//test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "//test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") } @@ -3384,7 +3383,7 @@ func Test_Ctx_SendFile_404(t *testing.T) { return err }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, StatusNotFound, resp.StatusCode) } @@ -3424,11 +3423,11 @@ func Test_Ctx_SendFile_Immutable(t *testing.T) { t.Run(endpoint, func(t *testing.T) { t.Parallel() // 1st try - resp, err := app.Test(httptest.NewRequest(MethodGet, endpoint, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, endpoint, nil)) require.NoError(t, err) require.Equal(t, StatusOK, resp.StatusCode) // 2nd try - resp, err = app.Test(httptest.NewRequest(MethodGet, endpoint, http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, endpoint, nil)) require.NoError(t, err) require.Equal(t, StatusOK, resp.StatusCode) }) @@ -3446,9 +3445,9 @@ func Test_Ctx_SendFile_RestoreOriginalURL(t *testing.T) { return err }) - _, err1 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", http.NoBody)) + _, err1 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", nil)) // second request required to confirm with zero allocation - _, err2 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", http.NoBody)) + _, err2 := app.Test(httptest.NewRequest(MethodGet, "/?test=true", nil)) require.NoError(t, err1) require.NoError(t, err2) @@ -3761,7 +3760,7 @@ func Test_Ctx_Next(t *testing.T) { c.Set("X-Next-Result", "Works") return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.Equal(t, "Works", resp.Header.Get("X-Next-Result")) @@ -3776,7 +3775,7 @@ func Test_Ctx_Next_Error(t *testing.T) { return ErrNotFound }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") require.Equal(t, "Works", resp.Header.Get("X-Next-Result")) @@ -4018,7 +4017,7 @@ func Test_Ctx_RestartRouting(t *testing.T) { } return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.Equal(t, 3, calls, "Number of calls") @@ -4043,7 +4042,7 @@ func Test_Ctx_RestartRoutingWithChangedPath(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.False(t, executedOldHandler, "Executed old handler") @@ -4066,7 +4065,7 @@ func Test_Ctx_RestartRoutingWithChangedPathAndCatchAll(t *testing.T) { return ErrNotFound }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "http://example.com/old", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") } @@ -4813,16 +4812,16 @@ func TestCtx_ParamsInt(t *testing.T) { return nil }) - _, err := app.Test(httptest.NewRequest(MethodGet, "/test/1111", http.NoBody)) + _, err := app.Test(httptest.NewRequest(MethodGet, "/test/1111", nil)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/testnoint/xd", http.NoBody)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/testnoint/xd", nil)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", http.NoBody)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", nil)) require.NoError(t, err) - _, err = app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", http.NoBody)) + _, err = app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", nil)) require.NoError(t, err) } diff --git a/middleware/adaptor/adaptor_test.go b/middleware/adaptor/adaptor_test.go index 544b5baabb..a14ea60669 100644 --- a/middleware/adaptor/adaptor_test.go +++ b/middleware/adaptor/adaptor_test.go @@ -396,7 +396,7 @@ func Test_ConvertRequest(t *testing.T) { return c.SendString("Request URL: " + httpReq.URL.String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test?hello=world&another=test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test?hello=world&another=test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, http.StatusOK, resp.StatusCode, "Status code") @@ -453,7 +453,7 @@ func Benchmark_FiberHandlerFunc(b *testing.B) { r := http.Request{ Method: http.MethodPost, - Body: http.NoBody, + Body: nil, } // Replace the empty Body with our buffer @@ -520,7 +520,7 @@ func Benchmark_FiberHandlerFunc_Parallel(b *testing.B) { w := httptest.NewRecorder() r := http.Request{ Method: http.MethodPost, - Body: http.NoBody, + Body: nil, } // Replace the empty Body with our buffer diff --git a/middleware/basicauth/basicauth_test.go b/middleware/basicauth/basicauth_test.go index 0f8a86e660..421fcfd8dd 100644 --- a/middleware/basicauth/basicauth_test.go +++ b/middleware/basicauth/basicauth_test.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "fmt" "io" - "net/http" "net/http/httptest" "testing" @@ -23,7 +22,7 @@ func Test_BasicAuth_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -76,7 +75,7 @@ func Test_Middleware_BasicAuth(t *testing.T) { // Base64 encode credentials for http auth header creds := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%s", tt.username, tt.password))) - req := httptest.NewRequest(fiber.MethodGet, "/testauth", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/testauth", nil) req.Header.Add("Authorization", "Basic "+creds) resp, err := app.Test(req) require.NoError(t, err) diff --git a/middleware/cache/cache_test.go b/middleware/cache/cache_test.go index e21d43a49d..1beee76d62 100644 --- a/middleware/cache/cache_test.go +++ b/middleware/cache/cache_test.go @@ -7,7 +7,6 @@ import ( "fmt" "io" "math" - "net/http" "net/http/httptest" "os" "strconv" @@ -36,10 +35,10 @@ func Test_Cache_CacheControl(t *testing.T) { return c.SendString("Hello, World!") }) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "public, max-age=10", resp.Header.Get(fiber.HeaderCacheControl)) } @@ -54,7 +53,7 @@ func Test_Cache_Expired(t *testing.T) { return c.SendString(strconv.FormatInt(time.Now().UnixNano(), 10)) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -62,7 +61,7 @@ func Test_Cache_Expired(t *testing.T) { // Sleep until the cache is expired time.Sleep(3 * time.Second) - respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) bodyCached, err := io.ReadAll(respCached.Body) require.NoError(t, err) @@ -72,7 +71,7 @@ func Test_Cache_Expired(t *testing.T) { } // Next response should be also cached - respCachedNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + respCachedNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) bodyCachedNextRound, err := io.ReadAll(respCachedNextRound.Body) require.NoError(t, err) @@ -93,11 +92,11 @@ func Test_Cache(t *testing.T) { return c.SendString(now) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) - cachedReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/", nil) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) @@ -121,7 +120,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { }) // Request id = 1 - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) body, err := io.ReadAll(resp.Body) @@ -131,7 +130,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { // Response cached, entry id = 1 // Request id = 2 without Cache-Control: no-cache - cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) cachedBody, err := io.ReadAll(cachedResp.Body) @@ -141,7 +140,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { // Response not cached, returns cached response, entry id = 1 // Request id = 2 with Cache-Control: no-cache - noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) noCacheReq.Header.Set(fiber.HeaderCacheControl, noCache) noCacheResp, err := app.Test(noCacheReq) require.NoError(t, err) @@ -153,7 +152,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { /* Check Test_Cache_WithETagAndNoCacheRequestDirective */ // Request id = 2 with Cache-Control: no-cache again - noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) noCacheReq1.Header.Set(fiber.HeaderCacheControl, noCache) noCacheResp1, err := app.Test(noCacheReq1) require.NoError(t, err) @@ -164,7 +163,7 @@ func Test_Cache_WithNoCacheRequestDirective(t *testing.T) { // Response cached, returns updated response, entry = 2 // Request id = 1 without Cache-Control: no-cache - cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", nil) cachedResp1, err := app.Test(cachedReq1) require.NoError(t, err) cachedBody1, err := io.ReadAll(cachedResp1.Body) @@ -189,7 +188,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { }) // Request id = 1 - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("X-Cache")) @@ -200,7 +199,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { etagToken := resp.Header.Get("Etag") // Request id = 2 with ETag but without Cache-Control: no-cache - cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) cachedReq.Header.Set(fiber.HeaderIfNoneMatch, etagToken) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) @@ -209,7 +208,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { // Response not cached, returns cached response, entry id = 1, status not modified // Request id = 2 with ETag and Cache-Control: no-cache - noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + noCacheReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) noCacheReq.Header.Set(fiber.HeaderCacheControl, noCache) noCacheReq.Header.Set(fiber.HeaderIfNoneMatch, etagToken) noCacheResp, err := app.Test(noCacheReq) @@ -222,7 +221,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { etagToken = noCacheResp.Header.Get("Etag") // Request id = 2 with ETag and Cache-Control: no-cache again - noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + noCacheReq1 := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) noCacheReq1.Header.Set(fiber.HeaderCacheControl, noCache) noCacheReq1.Header.Set(fiber.HeaderIfNoneMatch, etagToken) noCacheResp1, err := app.Test(noCacheReq1) @@ -232,7 +231,7 @@ func Test_Cache_WithETagAndNoCacheRequestDirective(t *testing.T) { // Response cached, returns updated response, entry id = 2, status not modified // Request id = 1 without ETag and Cache-Control: no-cache - cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + cachedReq1 := httptest.NewRequest(fiber.MethodGet, "/", nil) cachedResp1, err := app.Test(cachedReq1) require.NoError(t, err) require.Equal(t, cacheHit, cachedResp1.Header.Get("X-Cache")) @@ -252,7 +251,7 @@ func Test_Cache_WithNoStoreRequestDirective(t *testing.T) { }) // Request id = 2 - noStoreReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", http.NoBody) + noStoreReq := httptest.NewRequest(fiber.MethodGet, "/?id=2", nil) noStoreReq.Header.Set(fiber.HeaderCacheControl, noStore) noStoreResp, err := app.Test(noStoreReq) require.NoError(t, err) @@ -279,7 +278,7 @@ func Test_Cache_WithSeveralRequests(t *testing.T) { for runs := 0; runs < 10; runs++ { for i := 0; i < 10; i++ { func(id int) { - rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, fmt.Sprintf("/%d", id), http.NoBody)) + rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, fmt.Sprintf("/%d", id), nil)) require.NoError(t, err) defer func(body io.ReadCloser) { @@ -312,11 +311,11 @@ func Test_Cache_Invalid_Expiration(t *testing.T) { return c.SendString(now) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) - cachedReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + cachedReq := httptest.NewRequest(fiber.MethodGet, "/", nil) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) @@ -343,25 +342,25 @@ func Test_Cache_Get(t *testing.T) { return c.SendString(fiber.Query[string](c, "cache")) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "12345", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) @@ -385,25 +384,25 @@ func Test_Cache_Post(t *testing.T) { return c.SendString(fiber.Query[string](c, "cache")) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=123", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=123", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) require.Equal(t, "123", string(body)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/get?cache=12345", nil)) require.NoError(t, err) body, err = io.ReadAll(resp.Body) require.NoError(t, err) @@ -421,14 +420,14 @@ func Test_Cache_NothingToCache(t *testing.T) { return c.SendString(time.Now().String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) time.Sleep(500 * time.Millisecond) - respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) bodyCached, err := io.ReadAll(respCached.Body) require.NoError(t, err) @@ -458,22 +457,22 @@ func Test_Cache_CustomNext(t *testing.T) { return c.Status(fiber.StatusInternalServerError).SendString(time.Now().String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) require.NoError(t, err) - respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + respCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) bodyCached, err := io.ReadAll(respCached.Body) require.NoError(t, err) require.True(t, bytes.Equal(body, bodyCached)) require.NotEmpty(t, respCached.Header.Get(fiber.HeaderCacheControl)) - _, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/error", http.NoBody)) + _, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/error", nil)) require.NoError(t, err) - errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", http.NoBody)) + errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", nil)) require.NoError(t, err) require.Empty(t, errRespCached.Header.Get(fiber.HeaderCacheControl)) } @@ -492,7 +491,7 @@ func Test_CustomKey(t *testing.T) { return c.SendString("hi") }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) _, err := app.Test(req) require.NoError(t, err) require.True(t, called) @@ -517,7 +516,7 @@ func Test_CustomExpiration(t *testing.T) { return c.SendString(strconv.FormatInt(time.Now().UnixNano(), 10)) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.True(t, called) require.Equal(t, 1, newCacheTime) @@ -525,7 +524,7 @@ func Test_CustomExpiration(t *testing.T) { // Sleep until the cache is expired time.Sleep(1 * time.Second) - cachedResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + cachedResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) body, err := io.ReadAll(resp.Body) @@ -538,7 +537,7 @@ func Test_CustomExpiration(t *testing.T) { } // Next response should be cached - cachedRespNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + cachedRespNextRound, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) cachedBodyNextRound, err := io.ReadAll(cachedRespNextRound.Body) require.NoError(t, err) @@ -561,12 +560,12 @@ func Test_AdditionalE2EResponseHeaders(t *testing.T) { return c.SendString("hi") }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) require.Equal(t, "foobar", resp.Header.Get("X-Foobar")) - req = httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req = httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err = app.Test(req) require.NoError(t, err) require.Equal(t, "foobar", resp.Header.Get("X-Foobar")) @@ -596,19 +595,19 @@ func Test_CacheHeader(t *testing.T) { return c.Status(fiber.StatusInternalServerError).SendString(time.Now().String()) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("X-Cache")) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, cacheHit, resp.Header.Get("X-Cache")) - resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/?cache=12345", nil)) require.NoError(t, err) require.Equal(t, cacheUnreachable, resp.Header.Get("X-Cache")) - errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", http.NoBody)) + errRespCached, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/error", nil)) require.NoError(t, err) require.Equal(t, cacheUnreachable, errRespCached.Header.Get("X-Cache")) } @@ -625,12 +624,12 @@ func Test_Cache_WithHead(t *testing.T) { } app.Route("/").Get(handler).Head(handler) - req := httptest.NewRequest(fiber.MethodHead, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodHead, "/", nil) resp, err := app.Test(req) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("X-Cache")) - cachedReq := httptest.NewRequest(fiber.MethodHead, "/", http.NoBody) + cachedReq := httptest.NewRequest(fiber.MethodHead, "/", nil) cachedResp, err := app.Test(cachedReq) require.NoError(t, err) require.Equal(t, cacheHit, cachedResp.Header.Get("X-Cache")) @@ -654,28 +653,28 @@ func Test_Cache_WithHeadThenGet(t *testing.T) { } app.Route("/").Get(handler).Head(handler) - headResp, err := app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", http.NoBody)) + headResp, err := app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", nil)) require.NoError(t, err) headBody, err := io.ReadAll(headResp.Body) require.NoError(t, err) require.Equal(t, "", string(headBody)) require.Equal(t, cacheMiss, headResp.Header.Get("X-Cache")) - headResp, err = app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", http.NoBody)) + headResp, err = app.Test(httptest.NewRequest(fiber.MethodHead, "/?cache=123", nil)) require.NoError(t, err) headBody, err = io.ReadAll(headResp.Body) require.NoError(t, err) require.Equal(t, "", string(headBody)) require.Equal(t, cacheHit, headResp.Header.Get("X-Cache")) - getResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", http.NoBody)) + getResp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", nil)) require.NoError(t, err) getBody, err := io.ReadAll(getResp.Body) require.NoError(t, err) require.Equal(t, "123", string(getBody)) require.Equal(t, cacheMiss, getResp.Header.Get("X-Cache")) - getResp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", http.NoBody)) + getResp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/?cache=123", nil)) require.NoError(t, err) getBody, err = io.ReadAll(getResp.Body) require.NoError(t, err) @@ -696,7 +695,7 @@ func Test_CustomCacheHeader(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, cacheMiss, resp.Header.Get("Cache-Status")) } @@ -743,7 +742,7 @@ func Test_Cache_MaxBytesOrder(t *testing.T) { } for idx, tcase := range cases { - rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], http.NoBody)) + rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], nil)) require.NoError(t, err) require.Equal(t, tcase[1], rsp.Header.Get("X-Cache"), fmt.Sprintf("Case %v", idx)) } @@ -778,7 +777,7 @@ func Test_Cache_MaxBytesSizes(t *testing.T) { } for idx, tcase := range cases { - rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], http.NoBody)) + rsp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tcase[0], nil)) require.NoError(t, err) require.Equal(t, tcase[1], rsp.Header.Get("X-Cache"), fmt.Sprintf("Case %v", idx)) } diff --git a/middleware/compress/compress_test.go b/middleware/compress/compress_test.go index 3bdc71da0b..2d85e790c6 100644 --- a/middleware/compress/compress_test.go +++ b/middleware/compress/compress_test.go @@ -4,7 +4,6 @@ import ( "errors" "fmt" "io" - "net/http" "net/http/httptest" "os" "testing" @@ -35,7 +34,7 @@ func Test_Compress_Gzip(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req) @@ -66,7 +65,7 @@ func Test_Compress_Different_Level(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req) @@ -92,7 +91,7 @@ func Test_Compress_Deflate(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Set("Accept-Encoding", "deflate") resp, err := app.Test(req) @@ -116,7 +115,7 @@ func Test_Compress_Brotli(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Set("Accept-Encoding", "br") resp, err := app.Test(req, 10000) @@ -140,7 +139,7 @@ func Test_Compress_Disabled(t *testing.T) { return c.Send(filedata) }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Set("Accept-Encoding", "br") resp, err := app.Test(req) @@ -164,7 +163,7 @@ func Test_Compress_Next_Error(t *testing.T) { return errors.New("next error") }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Set("Accept-Encoding", "gzip") resp, err := app.Test(req) @@ -187,7 +186,7 @@ func Test_Compress_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 1ba213fcdc..3d3ae8c655 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -1,7 +1,6 @@ package cors import ( - "net/http" "net/http/httptest" "strings" "testing" @@ -340,7 +339,7 @@ func Test_CORS_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } diff --git a/middleware/csrf/csrf_test.go b/middleware/csrf/csrf_test.go index 277ac3f002..99cbf85e48 100644 --- a/middleware/csrf/csrf_test.go +++ b/middleware/csrf/csrf_test.go @@ -1,7 +1,6 @@ package csrf import ( - "net/http" "net/http/httptest" "strings" "testing" @@ -375,7 +374,7 @@ func Test_CSRF_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -949,7 +948,7 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // return c.SendStatus(fiber.StatusOK) // }) -// resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) +// resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) // require.NoError(t, err) // require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -964,11 +963,11 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // fmt.Println("token", token) -// getReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) +// getReq := httptest.NewRequest(fiber.MethodGet, "/", nil) // getReq.Header.Set(HeaderName, token) // resp, err = app.Test(getReq) -// getReq = httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody) +// getReq = httptest.NewRequest(fiber.MethodGet, "/test", nil) // getReq.Header.Set("X-Requested-With", "XMLHttpRequest") // getReq.Header.Set(fiber.HeaderCacheControl, "no") // getReq.Header.Set(HeaderName, token) @@ -979,7 +978,7 @@ func Test_CSRF_Cookie_Injection_Exploit(t *testing.T) { // getReq.Header.Del(HeaderName) // resp, err = app.Test(getReq) -// postReq := httptest.NewRequest(fiber.MethodPost, "/", http.NoBody) +// postReq := httptest.NewRequest(fiber.MethodPost, "/", nil) // postReq.Header.Set("X-Requested-With", "XMLHttpRequest") // postReq.Header.Set(HeaderName, token) // resp, err = app.Test(postReq) diff --git a/middleware/earlydata/earlydata_test.go b/middleware/earlydata/earlydata_test.go index 4c6d76258e..9a62bf2524 100644 --- a/middleware/earlydata/earlydata_test.go +++ b/middleware/earlydata/earlydata_test.go @@ -3,7 +3,6 @@ package earlydata_test import ( "errors" "fmt" - "net/http" "net/http/httptest" "testing" @@ -89,7 +88,7 @@ func Test_EarlyData(t *testing.T) { t.Helper() { - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) @@ -107,7 +106,7 @@ func Test_EarlyData(t *testing.T) { } { - req := httptest.NewRequest(fiber.MethodPost, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodPost, "/", nil) resp, err := app.Test(req) require.NoError(t, err) @@ -129,7 +128,7 @@ func Test_EarlyData(t *testing.T) { t.Helper() { - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) resp, err := app.Test(req) require.NoError(t, err) @@ -147,7 +146,7 @@ func Test_EarlyData(t *testing.T) { } { - req := httptest.NewRequest(fiber.MethodPost, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodPost, "/", nil) resp, err := app.Test(req) require.NoError(t, err) diff --git a/middleware/encryptcookie/encryptcookie_test.go b/middleware/encryptcookie/encryptcookie_test.go index 046ba9ca1b..ee7ca9ae60 100644 --- a/middleware/encryptcookie/encryptcookie_test.go +++ b/middleware/encryptcookie/encryptcookie_test.go @@ -2,7 +2,6 @@ package encryptcookie import ( "encoding/base64" - "net/http" "net/http/httptest" "testing" @@ -93,7 +92,7 @@ func Test_Encrypt_Cookie_Next(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "SomeThing", resp.Cookies()[0].Value) } diff --git a/middleware/etag/etag_test.go b/middleware/etag/etag_test.go index ebdea0f422..9769639cb1 100644 --- a/middleware/etag/etag_test.go +++ b/middleware/etag/etag_test.go @@ -3,7 +3,6 @@ package etag import ( "bytes" "io" - "net/http" "net/http/httptest" "testing" @@ -22,7 +21,7 @@ func Test_ETag_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -38,7 +37,7 @@ func Test_ETag_SkipError(t *testing.T) { return fiber.ErrForbidden }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusForbidden, resp.StatusCode) } @@ -54,7 +53,7 @@ func Test_ETag_NotStatusOK(t *testing.T) { return c.SendStatus(fiber.StatusCreated) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusCreated, resp.StatusCode) } @@ -70,7 +69,7 @@ func Test_ETag_NoBody(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) } @@ -103,7 +102,7 @@ func testETagNewEtag(t *testing.T, headerIfNoneMatch, matched bool) { //nolint:r return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) if headerIfNoneMatch { etag := `"non-match"` if matched { @@ -157,7 +156,7 @@ func testETagWeakEtag(t *testing.T, headerIfNoneMatch, matched bool) { //nolint: return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) if headerIfNoneMatch { etag := `W/"non-match"` if matched { @@ -215,7 +214,7 @@ func testETagCustomEtag(t *testing.T, headerIfNoneMatch, matched bool) { //nolin return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) if headerIfNoneMatch { etag := `"non-match"` if matched { @@ -256,7 +255,7 @@ func Test_ETag_CustomEtagPut(t *testing.T) { return c.SendString("Hello, World!") }) - req := httptest.NewRequest(fiber.MethodPut, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodPut, "/", nil) req.Header.Set(fiber.HeaderIfMatch, `"non-match"`) resp, err := app.Test(req) require.NoError(t, err) diff --git a/middleware/expvar/expvar_test.go b/middleware/expvar/expvar_test.go index e6caa3b82a..a55198255f 100644 --- a/middleware/expvar/expvar_test.go +++ b/middleware/expvar/expvar_test.go @@ -3,7 +3,6 @@ package expvar import ( "bytes" "io" - "net/http" "net/http/httptest" "testing" @@ -21,7 +20,7 @@ func Test_Non_Expvar_Path(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -40,7 +39,7 @@ func Test_Expvar_Index(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMEApplicationJSONCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -61,7 +60,7 @@ func Test_Expvar_Filter(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars?r=cmd", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars?r=cmd", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMEApplicationJSONCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -82,7 +81,7 @@ func Test_Expvar_Other_Path(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars/302", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars/302", nil)) require.NoError(t, err) require.Equal(t, 302, resp.StatusCode) } @@ -98,7 +97,7 @@ func Test_Expvar_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars", nil)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } diff --git a/middleware/favicon/favicon_test.go b/middleware/favicon/favicon_test.go index 5d2c719298..ecf550b2a3 100644 --- a/middleware/favicon/favicon_test.go +++ b/middleware/favicon/favicon_test.go @@ -24,19 +24,19 @@ func Test_Middleware_Favicon(t *testing.T) { }) // Skip Favicon middleware - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusNoContent, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(fiber.MethodOptions, "/favicon.ico", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodOptions, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(fiber.MethodPut, "/favicon.ico", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodPut, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusMethodNotAllowed, resp.StatusCode, "Status code") require.Equal(t, "GET, HEAD, OPTIONS", resp.Header.Get(fiber.HeaderAllow)) @@ -69,7 +69,7 @@ func Test_Middleware_Favicon_Found(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -89,7 +89,7 @@ func Test_Custom_Favicon_URL(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(http.MethodGet, customURL, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(http.MethodGet, customURL, nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") @@ -111,7 +111,7 @@ func Test_Custom_Favicon_Data(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -128,7 +128,7 @@ func Test_Middleware_Favicon_FileSystem(t *testing.T) { FileSystem: os.DirFS("../../.github/testdata"), })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -145,7 +145,7 @@ func Test_Middleware_Favicon_CacheControl(t *testing.T) { File: "../../.github/testdata/favicon.ico", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/favicon.ico", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") require.Equal(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) @@ -181,7 +181,7 @@ func Test_Favicon_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } diff --git a/middleware/filesystem/filesystem_test.go b/middleware/filesystem/filesystem_test.go index 50a8661cad..feccdd128f 100644 --- a/middleware/filesystem/filesystem_test.go +++ b/middleware/filesystem/filesystem_test.go @@ -122,7 +122,7 @@ func Test_FileSystem(t *testing.T) { tt := tt t.Run(tt.name, func(t *testing.T) { t.Parallel() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tt.url, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, tt.url, nil)) require.NoError(t, err) require.Equal(t, tt.statusCode, resp.StatusCode) @@ -145,7 +145,7 @@ func Test_FileSystem_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -158,7 +158,7 @@ func Test_FileSystem_Download(t *testing.T) { Download: true, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/img/fiber.png", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/img/fiber.png", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.NotEmpty(t, resp.Header.Get(fiber.HeaderContentLength)) @@ -174,7 +174,7 @@ func Test_FileSystem_NonGetAndHead(t *testing.T) { Root: os.DirFS("../../.github/testdata/fs"), })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/test", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/test", nil)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } @@ -202,7 +202,7 @@ func Test_FileSystem_NoRoot(t *testing.T) { app := fiber.New() app.Use(New()) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) } @@ -245,7 +245,7 @@ func Test_FileSystem_UsingContentTypeCharset(t *testing.T) { ContentTypeCharset: "UTF-8", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, "text/html; charset=UTF-8", resp.Header.Get("Content-Type")) diff --git a/middleware/healthcheck/healthcheck_test.go b/middleware/healthcheck/healthcheck_test.go index f9f749eab4..409b985a60 100644 --- a/middleware/healthcheck/healthcheck_test.go +++ b/middleware/healthcheck/healthcheck_test.go @@ -1,7 +1,6 @@ package healthcheck import ( - "net/http" "net/http/httptest" "strconv" "testing" @@ -13,7 +12,7 @@ import ( func shouldGiveStatus(t *testing.T, app *fiber.App, path string, expectedStatus int) { t.Helper() - req, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, http.NoBody)) + req, err := app.Test(httptest.NewRequest(fiber.MethodGet, path, nil)) require.NoError(t, err) require.Equal(t, expectedStatus, req.StatusCode, "path: "+path+" should match "+strconv.Itoa(expectedStatus)) } @@ -145,12 +144,12 @@ func Test_HealthCheck_Custom(t *testing.T) { // Live should return 200 with GET request shouldGiveOK(t, app, "/live") // Live should return 404 with POST request - req, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/live", http.NoBody)) + req, err := app.Test(httptest.NewRequest(fiber.MethodPost, "/live", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) // Ready should return 404 with POST request - req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", http.NoBody)) + req, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/ready", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, req.StatusCode) diff --git a/middleware/helmet/helmet_test.go b/middleware/helmet/helmet_test.go index b2c8305205..c9d4b1c457 100644 --- a/middleware/helmet/helmet_test.go +++ b/middleware/helmet/helmet_test.go @@ -1,7 +1,6 @@ package helmet import ( - "net/http" "net/http/httptest" "testing" @@ -18,7 +17,7 @@ func Test_Default(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "0", resp.Header.Get(fiber.HeaderXXSSProtection)) require.Equal(t, "nosniff", resp.Header.Get(fiber.HeaderXContentTypeOptions)) @@ -62,7 +61,7 @@ func Test_CustomValues_AllHeaders(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) // Assertions for custom header values require.Equal(t, "0", resp.Header.Get(fiber.HeaderXXSSProtection)) @@ -107,7 +106,7 @@ func Test_RealWorldValues_AllHeaders(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) // Assertions for real-world header values require.Equal(t, "0", resp.Header.Get(fiber.HeaderXXSSProtection)) @@ -142,11 +141,11 @@ func Test_Next(t *testing.T) { return c.SendString("Skipped!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "no-referrer", resp.Header.Get(fiber.HeaderReferrerPolicy)) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/next", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/next", nil)) require.NoError(t, err) require.Equal(t, "", resp.Header.Get(fiber.HeaderReferrerPolicy)) } @@ -162,7 +161,7 @@ func Test_ContentSecurityPolicy(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "default-src 'none'", resp.Header.Get(fiber.HeaderContentSecurityPolicy)) } @@ -179,7 +178,7 @@ func Test_ContentSecurityPolicyReportOnly(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "default-src 'none'", resp.Header.Get(fiber.HeaderContentSecurityPolicyReportOnly)) require.Equal(t, "", resp.Header.Get(fiber.HeaderContentSecurityPolicy)) @@ -196,7 +195,7 @@ func Test_PermissionsPolicy(t *testing.T) { return c.SendString("Hello, World!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, "microphone=()", resp.Header.Get(fiber.HeaderPermissionsPolicy)) } diff --git a/middleware/idempotency/idempotency_test.go b/middleware/idempotency/idempotency_test.go index e05f5d0da1..f4d52d3c29 100644 --- a/middleware/idempotency/idempotency_test.go +++ b/middleware/idempotency/idempotency_test.go @@ -3,7 +3,6 @@ package idempotency_test import ( "errors" "io" - "net/http" "net/http/httptest" "strconv" "sync" @@ -82,7 +81,7 @@ func Test_Idempotency(t *testing.T) { }) doReq := func(method, route, idempotencyKey string) string { - req := httptest.NewRequest(method, route, http.NoBody) + req := httptest.NewRequest(method, route, nil) if idempotencyKey != "" { req.Header.Set("X-Idempotency-Key", idempotencyKey) } diff --git a/middleware/keyauth/keyauth_test.go b/middleware/keyauth/keyauth_test.go index 13e2741c33..5b8d7d57a6 100644 --- a/middleware/keyauth/keyauth_test.go +++ b/middleware/keyauth/keyauth_test.go @@ -285,7 +285,7 @@ func TestCustomSuccessAndFailureHandlers(t *testing.T) { }) // Create a request without an API key and send it to the app - res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) // Read the response body into a string @@ -297,7 +297,7 @@ func TestCustomSuccessAndFailureHandlers(t *testing.T) { require.Equal(t, "API key is invalid and request was handled by custom error handler", string(body)) // Create a request with a valid API key in the Authorization header - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Add("Authorization", "Bearer "+CorrectKey) // Send the request to the app @@ -334,7 +334,7 @@ func TestCustomNextFunc(t *testing.T) { }) // Create a request with the "/allowed" path and send it to the app - req := httptest.NewRequest(fiber.MethodGet, "/allowed", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/allowed", nil) res, err := app.Test(req) require.NoError(t, err) @@ -347,7 +347,7 @@ func TestCustomNextFunc(t *testing.T) { require.Equal(t, "API key is valid and request was allowed by custom filter", string(body)) // Create a request with a different path and send it to the app without correct key - req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", http.NoBody) + req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", nil) res, err = app.Test(req) require.NoError(t, err) @@ -360,7 +360,7 @@ func TestCustomNextFunc(t *testing.T) { require.Equal(t, string(body), ErrMissingOrMalformedAPIKey.Error()) // Create a request with a different path and send it to the app with correct key - req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", http.NoBody) + req = httptest.NewRequest(fiber.MethodGet, "/not-allowed", nil) req.Header.Add("Authorization", "Basic "+CorrectKey) res, err = app.Test(req) @@ -394,7 +394,7 @@ func TestAuthSchemeToken(t *testing.T) { }) // Create a request with a valid API key in the "Token" Authorization header - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Add("Authorization", "Token "+CorrectKey) // Send the request to the app @@ -430,7 +430,7 @@ func TestAuthSchemeBasic(t *testing.T) { }) // Create a request without an API key and Send the request to the app - res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + res, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) // Read the response body into a string @@ -442,7 +442,7 @@ func TestAuthSchemeBasic(t *testing.T) { require.Equal(t, string(body), ErrMissingOrMalformedAPIKey.Error()) // Create a request with a valid API key in the "Authorization" header using the "Basic" scheme - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Add("Authorization", "Basic "+CorrectKey) // Send the request to the app diff --git a/middleware/limiter/limiter_test.go b/middleware/limiter/limiter_test.go index 400f98faf0..7b88d1d521 100644 --- a/middleware/limiter/limiter_test.go +++ b/middleware/limiter/limiter_test.go @@ -2,7 +2,6 @@ package limiter import ( "io" - "net/http" "net/http/httptest" "sync" "testing" @@ -34,7 +33,7 @@ func Test_Limiter_Concurrency_Store(t *testing.T) { var wg sync.WaitGroup singleRequest := func(wg *sync.WaitGroup) { defer wg.Done() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -50,13 +49,13 @@ func Test_Limiter_Concurrency_Store(t *testing.T) { wg.Wait() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -80,7 +79,7 @@ func Test_Limiter_Concurrency(t *testing.T) { var wg sync.WaitGroup singleRequest := func(wg *sync.WaitGroup) { defer wg.Done() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -96,13 +95,13 @@ func Test_Limiter_Concurrency(t *testing.T) { wg.Wait() - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -127,21 +126,21 @@ func Test_Limiter_Fixed_Window_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -167,21 +166,21 @@ func Test_Limiter_Fixed_Window_Custom_Storage_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -206,21 +205,21 @@ func Test_Limiter_Sliding_Window_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -246,21 +245,21 @@ func Test_Limiter_Sliding_Window_Custom_Storage_No_Skip_Choices(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -284,21 +283,21 @@ func Test_Limiter_Fixed_Window_Skip_Failed_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -323,21 +322,21 @@ func Test_Limiter_Fixed_Window_Custom_Storage_Skip_Failed_Requests(t *testing.T) return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -361,21 +360,21 @@ func Test_Limiter_Sliding_Window_Skip_Failed_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -400,21 +399,21 @@ func Test_Limiter_Sliding_Window_Custom_Storage_Skip_Failed_Requests(t *testing. return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) } @@ -440,21 +439,21 @@ func Test_Limiter_Fixed_Window_Skip_Successful_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -481,21 +480,21 @@ func Test_Limiter_Fixed_Window_Custom_Storage_Skip_Successful_Requests(t *testin return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(3 * time.Second) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -521,21 +520,21 @@ func Test_Limiter_Sliding_Window_Skip_Successful_Requests(t *testing.T) { return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -562,21 +561,21 @@ func Test_Limiter_Sliding_Window_Custom_Storage_Skip_Successful_Requests(t *test return c.SendStatus(200) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/success", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) time.Sleep(4*time.Second + 500*time.Millisecond) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/fail", nil)) require.NoError(t, err) require.Equal(t, 400, resp.StatusCode) } @@ -618,7 +617,7 @@ func Test_Limiter_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -693,7 +692,7 @@ func Test_Sliding_Window(t *testing.T) { }) singleRequest := func(shouldFail bool) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) if shouldFail { require.NoError(t, err) require.Equal(t, 429, resp.StatusCode) diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index 1faf6acfb6..0fb35ad121 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -38,7 +38,7 @@ func Test_Logger(t *testing.T) { return errors.New("some random error") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) require.Equal(t, "some random error", buf.String()) @@ -71,21 +71,21 @@ func Test_Logger_locals(t *testing.T) { return c.SendStatus(fiber.StatusOK) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "johndoe", buf.String()) buf.Reset() - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/int", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/int", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "55", buf.String()) buf.Reset() - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/empty", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/empty", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "", buf.String()) @@ -101,7 +101,7 @@ func Test_Logger_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -122,7 +122,7 @@ func Test_Logger_Done(t *testing.T) { return ctx.SendStatus(fiber.StatusOK) }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/logging", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/logging", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -137,7 +137,7 @@ func Test_Logger_ErrorTimeZone(t *testing.T) { TimeZone: "invalid", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -159,7 +159,7 @@ func Test_Logger_ErrorOutput_WithoutColor(t *testing.T) { DisableColors: true, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) require.EqualValues(t, 2, *o) @@ -174,7 +174,7 @@ func Test_Logger_ErrorOutput(t *testing.T) { Output: o, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) require.EqualValues(t, 2, *o) @@ -195,7 +195,7 @@ func Test_Logger_All(t *testing.T) { // Alias colors colors := app.Config().ColorScheme - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) @@ -258,7 +258,7 @@ func Test_Logger_WithLatency(t *testing.T) { sleepDuration = 1 * tu.div // Create a new HTTP request to the test route - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int(2*time.Second)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int(2*time.Second)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -300,7 +300,7 @@ func Test_Logger_WithLatency_DefaultFormat(t *testing.T) { sleepDuration = 1 * tu.div // Create a new HTTP request to the test route - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int(2*time.Second)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int(2*time.Second)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -328,7 +328,7 @@ func Test_Query_Params(t *testing.T) { Output: buf, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar&baz=moz", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/?foo=bar&baz=moz", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) @@ -356,7 +356,7 @@ func Test_Response_Body(t *testing.T) { return c.Send([]byte("Post in test")) }) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) expectedGetResponse := "Sample response body" @@ -364,7 +364,7 @@ func Test_Response_Body(t *testing.T) { buf.Reset() // Reset buffer to test POST - _, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/test", http.NoBody)) + _, err = app.Test(httptest.NewRequest(fiber.MethodPost, "/test", nil)) require.NoError(t, err) expectedPostResponse := "Post in test" @@ -388,7 +388,7 @@ func Test_Logger_AppendUint(t *testing.T) { return c.SendString("hello") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "0 5 200", buf.String()) @@ -418,10 +418,10 @@ func Test_Logger_Data_Race(t *testing.T) { wg := &sync.WaitGroup{} wg.Add(1) go func() { - resp1, err1 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp1, err1 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) wg.Done() }() - resp2, err2 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp2, err2 = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) wg.Wait() require.NoError(t, err1) @@ -509,7 +509,7 @@ func Test_Response_Header(t *testing.T) { return c.SendString("Hello fiber!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -530,7 +530,7 @@ func Test_Req_Header(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello fiber!") }) - headerReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + headerReq := httptest.NewRequest(fiber.MethodGet, "/", nil) headerReq.Header.Add("test", "Hello fiber!") resp, err := app.Test(headerReq) @@ -553,7 +553,7 @@ func Test_ReqHeader_Header(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello fiber!") }) - reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", nil) reqHeaderReq.Header.Add("test", "Hello fiber!") resp, err := app.Test(reqHeaderReq) @@ -583,7 +583,7 @@ func Test_CustomTags(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { return c.SendString("Hello fiber!") }) - reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + reqHeaderReq := httptest.NewRequest(fiber.MethodGet, "/", nil) reqHeaderReq.Header.Add("test", "Hello fiber!") resp, err := app.Test(reqHeaderReq) @@ -626,7 +626,7 @@ func Test_Logger_ByteSent_Streaming(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "0 0 200", buf.String()) @@ -648,7 +648,7 @@ func Test_Logger_EnableColors(t *testing.T) { Output: o, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) require.EqualValues(t, 1, *o) diff --git a/middleware/pprof/pprof_test.go b/middleware/pprof/pprof_test.go index e5961cdccb..286f031e6e 100644 --- a/middleware/pprof/pprof_test.go +++ b/middleware/pprof/pprof_test.go @@ -3,7 +3,6 @@ package pprof import ( "bytes" "io" - "net/http" "net/http/httptest" "testing" @@ -20,7 +19,7 @@ func Test_Non_Pprof_Path(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -38,7 +37,7 @@ func Test_Non_Pprof_Path_WithPrefix(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) @@ -56,7 +55,7 @@ func Test_Pprof_Index(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMETextHTMLCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -75,7 +74,7 @@ func Test_Pprof_Index_WithPrefix(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", nil)) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) require.Equal(t, fiber.MIMETextHTMLCharsetUTF8, resp.Header.Get(fiber.HeaderContentType)) @@ -106,7 +105,7 @@ func Test_Pprof_Subs(t *testing.T) { if sub == "profile" { target += "?seconds=1" } - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, http.NoBody), 5000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, nil), 5000) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) }) @@ -134,7 +133,7 @@ func Test_Pprof_Subs_WithPrefix(t *testing.T) { if sub == "profile" { target += "?seconds=1" } - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, http.NoBody), 5000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, target, nil), 5000) require.NoError(t, err) require.Equal(t, 200, resp.StatusCode) }) @@ -150,7 +149,7 @@ func Test_Pprof_Other(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/302", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/302", nil)) require.NoError(t, err) require.Equal(t, 302, resp.StatusCode) } @@ -164,7 +163,7 @@ func Test_Pprof_Other_WithPrefix(t *testing.T) { return c.SendString("escaped") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/302", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/302", nil)) require.NoError(t, err) require.Equal(t, 302, resp.StatusCode) } @@ -179,7 +178,7 @@ func Test_Pprof_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/", nil)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } @@ -195,7 +194,7 @@ func Test_Pprof_Next_WithPrefix(t *testing.T) { Prefix: "/federated-fiber", })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/", nil)) require.NoError(t, err) require.Equal(t, 404, resp.StatusCode) } diff --git a/middleware/proxy/proxy_test.go b/middleware/proxy/proxy_test.go index 340d9ee2b0..408ee71a5f 100644 --- a/middleware/proxy/proxy_test.go +++ b/middleware/proxy/proxy_test.go @@ -5,7 +5,6 @@ import ( "errors" "io" "net" - "net/http" "net/http/httptest" "strings" "testing" @@ -77,7 +76,7 @@ func Test_Proxy_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -90,7 +89,7 @@ func Test_Proxy(t *testing.T) { return c.SendStatus(fiber.StatusTeapot) }) - resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) + resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) @@ -98,7 +97,7 @@ func Test_Proxy(t *testing.T) { app.Use(Balancer(Config{Servers: []string{addr}})) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Host = addr resp, err = app.Test(req) require.NoError(t, err) @@ -195,7 +194,7 @@ func Test_Proxy_Forward(t *testing.T) { app.Use(Forward("http://" + addr)) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -259,7 +258,7 @@ func Test_Proxy_Modify_Response(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -286,7 +285,7 @@ func Test_Proxy_Modify_Request(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -310,7 +309,7 @@ func Test_Proxy_Timeout_Slow_Server(t *testing.T) { Timeout: 600 * time.Millisecond, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -334,7 +333,7 @@ func Test_Proxy_With_Timeout(t *testing.T) { Timeout: 100 * time.Millisecond, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) @@ -356,7 +355,7 @@ func Test_Proxy_Buffer_Size_Response(t *testing.T) { app := fiber.New() app.Use(Balancer(Config{Servers: []string{addr}})) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) @@ -366,7 +365,7 @@ func Test_Proxy_Buffer_Size_Response(t *testing.T) { ReadBufferSize: 1024 * 8, })) - resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) } @@ -382,7 +381,7 @@ func Test_Proxy_Do_RestoreOriginalURL(t *testing.T) { app.Get("/test", func(c fiber.Ctx) error { return Do(c, "http://"+addr) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) require.NoError(t, err1) require.Equal(t, "/test", resp.Request.URL.String()) require.Equal(t, fiber.StatusOK, resp.StatusCode) @@ -399,7 +398,7 @@ func Test_Proxy_Do_WithRealURL(t *testing.T) { return Do(c, "https://www.google.com") }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) require.NoError(t, err1) require.Equal(t, fiber.StatusOK, resp.StatusCode) require.Equal(t, "/test", resp.Request.URL.String()) @@ -416,7 +415,7 @@ func Test_Proxy_Do_WithRedirect(t *testing.T) { return Do(c, "https://google.com") }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), 1500) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), 1500) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -432,7 +431,7 @@ func Test_Proxy_DoRedirects_RestoreOriginalURL(t *testing.T) { return DoRedirects(c, "http://google.com", 1) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), 1500) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), 1500) require.NoError(t, err1) _, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -448,7 +447,7 @@ func Test_Proxy_DoRedirects_TooManyRedirects(t *testing.T) { return DoRedirects(c, "http://google.com", 0) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), 1500) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), 1500) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -470,7 +469,7 @@ func Test_Proxy_DoTimeout_RestoreOriginalURL(t *testing.T) { return DoTimeout(c, "http://"+addr, time.Second) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -493,7 +492,7 @@ func Test_Proxy_DoTimeout_Timeout(t *testing.T) { return DoTimeout(c, "http://"+addr, time.Second) }) - _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int((1*time.Second)/time.Millisecond)) + _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int((1*time.Second)/time.Millisecond)) require.Equal(t, errors.New("test: timeout error 1000ms"), err1) } @@ -510,7 +509,7 @@ func Test_Proxy_DoDeadline_RestoreOriginalURL(t *testing.T) { return DoDeadline(c, "http://"+addr, time.Now().Add(time.Second)) }) - resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody)) + resp, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil)) require.NoError(t, err1) body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -533,7 +532,7 @@ func Test_Proxy_DoDeadline_PastDeadline(t *testing.T) { return DoDeadline(c, "http://"+addr, time.Now().Add(time.Second)) }) - _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", http.NoBody), int((1*time.Second)/time.Millisecond)) + _, err1 := app.Test(httptest.NewRequest(fiber.MethodGet, "/test", nil), int((1*time.Second)/time.Millisecond)) require.Equal(t, errors.New("test: timeout error 1000ms"), err1) } @@ -558,7 +557,7 @@ func Test_Proxy_Do_HTTP_Prefix_URL(t *testing.T) { return nil }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/http://"+addr, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/http://"+addr, nil)) require.NoError(t, err) s, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -630,7 +629,7 @@ func Test_ProxyBalancer_Custom_Client(t *testing.T) { return c.SendStatus(fiber.StatusTeapot) }) - resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody), 2000) + resp, err := target.Test(httptest.NewRequest(fiber.MethodGet, "/", nil), 2000) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) @@ -647,7 +646,7 @@ func Test_ProxyBalancer_Custom_Client(t *testing.T) { Timeout: time.Second, }})) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Host = addr resp, err = app.Test(req) require.NoError(t, err) @@ -701,7 +700,7 @@ func Test_Proxy_Balancer_Forward_Local(t *testing.T) { app.Use(BalancerForward([]string{addr})) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) diff --git a/middleware/recover/recover_test.go b/middleware/recover/recover_test.go index d28a0399bc..9b5962db90 100644 --- a/middleware/recover/recover_test.go +++ b/middleware/recover/recover_test.go @@ -1,7 +1,6 @@ package recover //nolint:predeclared // TODO: Rename to some non-builtin import ( - "net/http" "net/http/httptest" "testing" @@ -25,7 +24,7 @@ func Test_Recover(t *testing.T) { panic("Hi, I'm an error!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) } @@ -40,7 +39,7 @@ func Test_Recover_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) } @@ -56,7 +55,7 @@ func Test_Recover_EnableStackTrace(t *testing.T) { panic("Hi, I'm an error!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/panic", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusInternalServerError, resp.StatusCode) } diff --git a/middleware/requestid/requestid_test.go b/middleware/requestid/requestid_test.go index 93facc5138..c739407be0 100644 --- a/middleware/requestid/requestid_test.go +++ b/middleware/requestid/requestid_test.go @@ -1,7 +1,6 @@ package requestid import ( - "net/http" "net/http/httptest" "testing" @@ -20,14 +19,14 @@ func Test_RequestID(t *testing.T) { return c.SendString("Hello, World 👋!") }) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) reqid := resp.Header.Get(fiber.HeaderXRequestID) require.Len(t, reqid, 36) - req := httptest.NewRequest(fiber.MethodGet, "/", http.NoBody) + req := httptest.NewRequest(fiber.MethodGet, "/", nil) req.Header.Add(fiber.HeaderXRequestID, reqid) resp, err = app.Test(req) @@ -46,7 +45,7 @@ func Test_RequestID_Next(t *testing.T) { }, })) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Empty(t, resp.Header.Get(fiber.HeaderXRequestID)) require.Equal(t, fiber.StatusNotFound, resp.StatusCode) @@ -71,7 +70,7 @@ func Test_RequestID_FromContext(t *testing.T) { return c.Next() }) - _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + _, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, reqID, ctxVal) } diff --git a/middleware/skip/skip_test.go b/middleware/skip/skip_test.go index 6e76afab84..cfa95f8cbc 100644 --- a/middleware/skip/skip_test.go +++ b/middleware/skip/skip_test.go @@ -1,7 +1,6 @@ package skip_test import ( - "net/http" "net/http/httptest" "testing" @@ -18,7 +17,7 @@ func Test_Skip(t *testing.T) { app.Use(skip.New(errTeapotHandler, func(fiber.Ctx) bool { return true })) app.Get("/", helloWorldHandler) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusOK, resp.StatusCode) } @@ -31,7 +30,7 @@ func Test_SkipFalse(t *testing.T) { app.Use(skip.New(errTeapotHandler, func(fiber.Ctx) bool { return false })) app.Get("/", helloWorldHandler) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) } @@ -44,7 +43,7 @@ func Test_SkipNilFunc(t *testing.T) { app.Use(skip.New(errTeapotHandler, nil)) app.Get("/", helloWorldHandler) - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil)) require.NoError(t, err) require.Equal(t, fiber.StatusTeapot, resp.StatusCode) } diff --git a/middleware/timeout/timeout_test.go b/middleware/timeout/timeout_test.go index 7b408b425c..b08445eb2a 100644 --- a/middleware/timeout/timeout_test.go +++ b/middleware/timeout/timeout_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "net/http" "net/http/httptest" "testing" "time" @@ -28,12 +27,12 @@ func Test_WithContextTimeout(t *testing.T) { }, 100*time.Millisecond) app.Get("/test/:sleepTime", h) testTimeout := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode, "Status code") } testSucces := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") } @@ -60,12 +59,12 @@ func Test_WithContextTimeoutWithCustomError(t *testing.T) { }, 100*time.Millisecond, ErrFooTimeOut) app.Get("/test/:sleepTime", h) testTimeout := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusRequestTimeout, resp.StatusCode, "Status code") } testSucces := func(timeoutStr string) { - resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/test/"+timeoutStr, nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, fiber.StatusOK, resp.StatusCode, "Status code") } diff --git a/mount_test.go b/mount_test.go index 540cedb207..b2c82c2952 100644 --- a/mount_test.go +++ b/mount_test.go @@ -7,7 +7,6 @@ package fiber import ( "errors" "io" - "net/http" "net/http/httptest" "testing" @@ -24,7 +23,7 @@ func Test_App_Mount(t *testing.T) { app := New() app.Use("/john", micro) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/john/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/john/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.Equal(t, uint32(1), app.handlersCount) @@ -44,7 +43,7 @@ func Test_App_Mount_RootPath_Nested(t *testing.T) { dynamic.Use("/api", apiserver) app.Use("/", dynamic) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/api/v1/home", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/api/v1/home", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.Equal(t, uint32(1), app.handlersCount) @@ -74,15 +73,15 @@ func Test_App_Mount_Nested(t *testing.T) { return c.SendStatus(StatusOK) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/one/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/one/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/one/two/nested", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/one/two/nested", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/one/two/three/test", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/one/two/three/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -99,7 +98,7 @@ func Test_App_Mount_Express_Behavior(t *testing.T) { } } testEndpoint := func(app *App, route, expectedBody string, expectedStatusCode int) { - resp, err := app.Test(httptest.NewRequest(MethodGet, route, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, route, nil)) require.NoError(t, err, "app.Test(req)") body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -144,7 +143,7 @@ func Test_App_Mount_Express_Behavior(t *testing.T) { func Test_App_Mount_RoutePositions(t *testing.T) { t.Parallel() testEndpoint := func(app *App, route, expectedBody string) { - resp, err := app.Test(httptest.NewRequest(MethodGet, route, http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, route, nil)) require.NoError(t, err, "app.Test(req)") body, err := io.ReadAll(resp.Body) require.NoError(t, err) @@ -244,7 +243,7 @@ func Test_App_ErrorHandler_GroupMount(t *testing.T) { v1 := app.Group("/v1") v1.Use("/john", micro) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", nil)) testErrorResponse(t, err, resp, "1: custom error") } @@ -264,7 +263,7 @@ func Test_App_ErrorHandler_GroupMountRootLevel(t *testing.T) { v1 := app.Group("/v1") v1.Use("/", micro) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", nil)) testErrorResponse(t, err, resp, "1: custom error") } @@ -280,7 +279,7 @@ func Test_App_Group_Mount(t *testing.T) { v1 := app.Group("/v1") v1.Use("/john", micro) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") require.Equal(t, uint32(1), app.handlersCount) @@ -301,7 +300,7 @@ func Test_App_UseParentErrorHandler(t *testing.T) { app.Use("/api", fiber) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/api", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/api", nil)) testErrorResponse(t, err, resp, "hi, i'm a custom error") } @@ -320,7 +319,7 @@ func Test_App_UseMountedErrorHandler(t *testing.T) { app.Use("/api", fiber) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/api", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/api", nil)) testErrorResponse(t, err, resp, "hi, i'm a custom error") } @@ -339,7 +338,7 @@ func Test_App_UseMountedErrorHandlerRootLevel(t *testing.T) { app.Use("/", fiber) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/api", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/api", nil)) testErrorResponse(t, err, resp, "hi, i'm a custom error") } @@ -381,7 +380,7 @@ func Test_App_UseMountedErrorHandlerForBestPrefixMatch(t *testing.T) { app.Use("/api", fiber) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/api/sub", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/api/sub", nil)) require.NoError(t, err, "/api/sub req") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -389,7 +388,7 @@ func Test_App_UseMountedErrorHandlerForBestPrefixMatch(t *testing.T) { require.NoError(t, err, "iotuil.ReadAll()") require.Equal(t, "hi, i'm a custom sub fiber error", string(b), "Response body") - resp2, err := app.Test(httptest.NewRequest(MethodGet, "/api/sub/third", http.NoBody)) + resp2, err := app.Test(httptest.NewRequest(MethodGet, "/api/sub/third", nil)) require.NoError(t, err, "/api/sub/third req") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -457,14 +456,14 @@ func Test_Mount_Route_Names(t *testing.T) { require.Equal(t, "/app2/users", route.Path) // GetRouteURL inside handler - req := httptest.NewRequest(MethodGet, "/app1/users", http.NoBody) + req := httptest.NewRequest(MethodGet, "/app1/users", nil) resp, err := rootApp.Test(req) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // ctx.App().GetRoute() inside handler - req = httptest.NewRequest(MethodPost, "/app1/users", http.NoBody) + req = httptest.NewRequest(MethodPost, "/app1/users", nil) resp, err = rootApp.Test(req) require.NoError(t, err, "app.Test(req)") @@ -492,7 +491,7 @@ func Test_Ctx_Render_Mount(t *testing.T) { app := New() app.Use("/hello", sub) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/hello/a", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/hello/a", nil)) require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.NoError(t, err, "app.Test(req)") @@ -548,7 +547,7 @@ func Test_Ctx_Render_Mount_ParentOrSubHasViews(t *testing.T) { sub.Use("/bruh", sub2) app.Use("/hello", sub) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/hello/world/a", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/hello/world/a", nil)) require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.NoError(t, err, "app.Test(req)") @@ -556,7 +555,7 @@ func Test_Ctx_Render_Mount_ParentOrSubHasViews(t *testing.T) { require.NoError(t, err) require.Equal(t, "

Hello a!

", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.NoError(t, err, "app.Test(req)") @@ -564,7 +563,7 @@ func Test_Ctx_Render_Mount_ParentOrSubHasViews(t *testing.T) { require.NoError(t, err) require.Equal(t, "

Hello, World!

", string(body)) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/hello/bruh/moment", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/hello/bruh/moment", nil)) require.Equal(t, StatusOK, resp.StatusCode, "Status code") require.NoError(t, err, "app.Test(req)") @@ -594,7 +593,7 @@ func Test_Ctx_Render_MountGroup(t *testing.T) { v1 := app.Group("/v1") v1.Use("/john", micro) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/john/doe", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") diff --git a/router_test.go b/router_test.go index cc46c492b1..5b29bbc3c2 100644 --- a/router_test.go +++ b/router_test.go @@ -9,7 +9,6 @@ import ( "errors" "fmt" "io" - "net/http" "net/http/httptest" "os" "testing" @@ -40,7 +39,7 @@ func Test_Route_Match_SameLength(t *testing.T) { return c.SendString(c.Params("param")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/:param", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/:param", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -49,7 +48,7 @@ func Test_Route_Match_SameLength(t *testing.T) { require.Equal(t, ":param", app.getString(body)) // with param - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -67,7 +66,7 @@ func Test_Route_Match_Star(t *testing.T) { return c.SendString(c.Params("*")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/*", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/*", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -76,7 +75,7 @@ func Test_Route_Match_Star(t *testing.T) { require.Equal(t, "*", app.getString(body)) // with param - resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -115,7 +114,7 @@ func Test_Route_Match_Root(t *testing.T) { return c.SendString("root") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -135,7 +134,7 @@ func Test_Route_Match_Parser(t *testing.T) { app.Get("/Foobar/*", func(c Ctx) error { return c.SendString(c.Params("*")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -144,7 +143,7 @@ func Test_Route_Match_Parser(t *testing.T) { require.Equal(t, "bar", app.getString(body)) // with star - resp, err = app.Test(httptest.NewRequest(MethodGet, "/Foobar/test", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/Foobar/test", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -162,7 +161,7 @@ func Test_Route_Match_Middleware(t *testing.T) { return c.SendString(c.Params("*")) }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/*", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/*", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -171,7 +170,7 @@ func Test_Route_Match_Middleware(t *testing.T) { require.Equal(t, "*", app.getString(body)) // with param - resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/bar/fasel", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/foo/bar/fasel", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -189,7 +188,7 @@ func Test_Route_Match_UnescapedPath(t *testing.T) { return c.SendString("test") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -197,13 +196,13 @@ func Test_Route_Match_UnescapedPath(t *testing.T) { require.NoError(t, err, "app.Test(req)") require.Equal(t, "test", app.getString(body)) // without special chars - resp, err = app.Test(httptest.NewRequest(MethodGet, "/créer", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/créer", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") // check deactivated behavior app.config.UnescapePath = false - resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/cr%C3%A9er", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusNotFound, resp.StatusCode, "Status code") } @@ -227,7 +226,7 @@ func Test_Route_Match_WithEscapeChar(t *testing.T) { }) // check static route - resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/some/resource/name:customVerb", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/v1/some/resource/name:customVerb", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -236,7 +235,7 @@ func Test_Route_Match_WithEscapeChar(t *testing.T) { require.Equal(t, "static", app.getString(body)) // check group route - resp, err = app.Test(httptest.NewRequest(MethodGet, "/v2/:firstVerb/:customVerb", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/v2/:firstVerb/:customVerb", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -245,7 +244,7 @@ func Test_Route_Match_WithEscapeChar(t *testing.T) { require.Equal(t, "group", app.getString(body)) // check param route - resp, err = app.Test(httptest.NewRequest(MethodGet, "/v3/awesome/name:customVerb", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/v3/awesome/name:customVerb", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, StatusOK, resp.StatusCode, "Status code") @@ -263,7 +262,7 @@ func Test_Route_Match_Middleware_HasPrefix(t *testing.T) { return c.SendString("middleware") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/foo/bar", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -281,7 +280,7 @@ func Test_Route_Match_Middleware_Root(t *testing.T) { return c.SendString("middleware") }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/everything", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/everything", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -342,11 +341,11 @@ func Test_Route_Static_Root(t *testing.T) { Browse: true, }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -357,11 +356,11 @@ func Test_Route_Static_Root(t *testing.T) { app = New() app.Static("/", dir) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/style.css", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -379,15 +378,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { Browse: true, }) - resp, err := app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) + resp, err := app.Test(httptest.NewRequest(MethodGet, "/static", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -400,15 +399,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { Browse: true, }) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -419,15 +418,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { app = New() app.Static("/static", dir) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") @@ -438,15 +437,15 @@ func Test_Route_Static_HasPrefix(t *testing.T) { app = New() app.Static("/static/", dir) - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 404, resp.StatusCode, "Status code") - resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", http.NoBody)) + resp, err = app.Test(httptest.NewRequest(MethodGet, "/static/style.css", nil)) require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") From ab2b0fc4c91c89c50560c6218625ab94c1bfb464 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Wed, 28 Feb 2024 14:20:30 +0100 Subject: [PATCH 50/51] fix(ctx pool): postpone the reset for some values shortly before the release in the pool --- ctx_interface.go | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/ctx_interface.go b/ctx_interface.go index a608604a53..54cf6012fa 100644 --- a/ctx_interface.go +++ b/ctx_interface.go @@ -459,22 +459,12 @@ func (app *App) ReleaseCtx(c Ctx) { // Reset is a method to reset context fields by given request when to use server handlers. func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx) { - // Reset route and handler index - c.indexRoute = -1 - c.indexHandler = 0 - - // Reset matched flag - c.matched = false - // Set paths c.pathOriginal = c.app.getString(fctx.URI().PathOriginal()) // Attach *fasthttp.RequestCtx to ctx c.setReq(fctx) - // reset base uri - c.baseURI = "" - // Set method c.method = c.app.getString(fctx.Request.Header.Method()) c.methodINT = c.app.methodInt(c.method) @@ -485,6 +475,16 @@ func (c *DefaultCtx) Reset(fctx *fasthttp.RequestCtx) { // Release is a method to reset context fields when to use ReleaseCtx() func (c *DefaultCtx) release() { + // Reset route and handler index + c.indexRoute = -1 + c.indexHandler = 0 + + // Reset matched flag + c.matched = false + + // reset base uri + c.baseURI = "" + c.route = nil c.fasthttp = nil c.bind = nil From ac643085a7aecef0f2649c8eceea57b230bff504 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Wed, 28 Feb 2024 15:39:22 +0100 Subject: [PATCH 51/51] refactor(tests): use testify panic method instead of custom solution --- log/default_test.go | 42 ++++++------------------------------------ 1 file changed, 6 insertions(+), 36 deletions(-) diff --git a/log/default_test.go b/log/default_test.go index ae106977ea..a0cb281497 100644 --- a/log/default_test.go +++ b/log/default_test.go @@ -56,19 +56,9 @@ func Test_DefaultLogger(t *testing.T) { Warn("work may fail") Error("work failed") - didPanic := false - func() { - defer func() { - if r := recover(); r != nil { - didPanic = true - } - }() + require.Panics(t, func() { Panic("work panic") - }() - - if !didPanic { - t.Errorf("Expected a panic when the panic logger method is called") - } + }) require.Equal(t, "[Trace] trace work\n"+ "[Debug] received work order\n"+ @@ -90,19 +80,9 @@ func Test_DefaultFormatLogger(t *testing.T) { Warnf("%s may fail", work) Errorf("%s failed", work) - didPanic := false - func() { - defer func() { - if r := recover(); r != nil { - didPanic = true - } - }() + require.Panics(t, func() { Panicf("%s panic", work) - }() - - if !didPanic { - t.Errorf("Expected a panic when the panic logger method is called") - } + }) require.Equal(t, "[Trace] trace work\n"+ "[Debug] received work order\n"+ @@ -126,19 +106,9 @@ func Test_CtxLogger(t *testing.T) { WithContext(ctx).Warnf("%s may fail", work) WithContext(ctx).Errorf("%s failed %d", work, 50) - didPanic := false - func() { - defer func() { - if r := recover(); r != nil { - didPanic = true - } - }() + require.Panics(t, func() { WithContext(ctx).Panicf("%s panic", work) - }() - - if !didPanic { - t.Errorf("Expected a panic when the panic logger method is called") - } + }) require.Equal(t, "[Trace] trace work\n"+ "[Debug] received work order\n"+