From e0bf65feb34c56622fdde3d62128ac330e0b91cb Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Fri, 9 Feb 2024 21:07:59 -0500 Subject: [PATCH 1/7] Update linter.yml --- .github/workflows/linter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/linter.yml b/.github/workflows/linter.yml index 4b2fba5888..dc7a9721de 100644 --- a/.github/workflows/linter.yml +++ b/.github/workflows/linter.yml @@ -33,4 +33,4 @@ jobs: uses: golangci/golangci-lint-action@v3 with: # NOTE: Keep this in sync with the version from .golangci.yml - version: v1.55.2 + version: v1.56.1 From b9a3cb85a9e84b3e327d4a19d76f73f70409e0af Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sat, 10 Feb 2024 17:05:05 -0500 Subject: [PATCH 2/7] Disable spancheck, fix some of the errors --- .golangci.yml | 2 ++ app_test.go | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 50b6c3d54f..249f5e6e0e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -159,6 +159,8 @@ issues: exclude-use-default: false linters: + disable: + - spancheck enable: - asasalint - asciicheck diff --git a/app_test.go b/app_test.go index 18016f1a8f..bd15c8dd8d 100644 --- a/app_test.go +++ b/app_test.go @@ -866,7 +866,7 @@ func Test_App_ShutdownWithContext(t *testing.T) { ln := fasthttputil.NewInmemoryListener() go func() { - require.NoError(t, app.Listener(ln)) + require.NoError(t, app.Listener(ln)) //nolint:testifylint // Needed for test }() time.Sleep(1 * time.Second) @@ -1543,7 +1543,7 @@ func Test_App_ReadTimeout(t *testing.T) { time.Sleep(500 * time.Millisecond) conn, err := net.Dial(NetworkTCP4, "127.0.0.1:4004") - require.NoError(t, err) + require.NoError(t, err) //nolint:testifylint // Needed for test defer func(conn net.Conn) { err := conn.Close() require.NoError(t, err) From ecc06f669de4421f242f84520aa40cda2c641746 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez Date: Sat, 10 Feb 2024 23:19:29 -0500 Subject: [PATCH 3/7] Fix ErrorAs, disable go-require from testifylint --- .golangci.yml | 4 ++++ app_test.go | 4 ++-- redirect_test.go | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 249f5e6e0e..37a32744df 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -11,6 +11,10 @@ output: sort-results: true linters-settings: + testifylint: + enable-all: true + disable: + - go-require errcheck: check-type-assertions: true check-blank: true diff --git a/app_test.go b/app_test.go index bd15c8dd8d..fdad171897 100644 --- a/app_test.go +++ b/app_test.go @@ -866,7 +866,7 @@ func Test_App_ShutdownWithContext(t *testing.T) { ln := fasthttputil.NewInmemoryListener() go func() { - require.NoError(t, app.Listener(ln)) //nolint:testifylint // Needed for test + require.NoError(t, app.Listener(ln)) }() time.Sleep(1 * time.Second) @@ -1543,7 +1543,7 @@ func Test_App_ReadTimeout(t *testing.T) { time.Sleep(500 * time.Millisecond) conn, err := net.Dial(NetworkTCP4, "127.0.0.1:4004") - require.NoError(t, err) //nolint:testifylint // Needed for test + require.NoError(t, err) defer func(conn net.Conn) { err := conn.Close() require.NoError(t, err) diff --git a/redirect_test.go b/redirect_test.go index 33241e3e5e..9b9cd4b204 100644 --- a/redirect_test.go +++ b/redirect_test.go @@ -146,7 +146,7 @@ func Test_Redirect_Back(t *testing.T) { err = c.Redirect().Back() require.Equal(t, 500, c.Response().StatusCode()) - require.ErrorAs(t, ErrRedirectBackNoFallback, &err) + require.ErrorAs(t, err, &ErrRedirectBackNoFallback) } // go test -run Test_Redirect_Back_WithReferer From 7f21bfcccba9ef3924b2d9194745db1a7df62a7e Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez Date: Sat, 10 Feb 2024 23:22:30 -0500 Subject: [PATCH 4/7] Remove extra space --- app_test.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/app_test.go b/app_test.go index fdad171897..18016f1a8f 100644 --- a/app_test.go +++ b/app_test.go @@ -866,7 +866,7 @@ func Test_App_ShutdownWithContext(t *testing.T) { ln := fasthttputil.NewInmemoryListener() go func() { - require.NoError(t, app.Listener(ln)) + require.NoError(t, app.Listener(ln)) }() time.Sleep(1 * time.Second) @@ -1543,7 +1543,7 @@ func Test_App_ReadTimeout(t *testing.T) { time.Sleep(500 * time.Millisecond) conn, err := net.Dial(NetworkTCP4, "127.0.0.1:4004") - require.NoError(t, err) + require.NoError(t, err) defer func(conn net.Conn) { err := conn.Close() require.NoError(t, err) From e248fdfeaa051c8132c64899d183172ab2ac36c1 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez Date: Sun, 11 Feb 2024 00:17:14 -0500 Subject: [PATCH 5/7] Fix all warnings from golangci-lint and revive unused params --- app_test.go | 18 ++--- client_test.go | 52 +++++++-------- ctx.go | 2 +- ctx_test.go | 20 +++--- helpers.go | 1 + helpers_test.go | 2 +- hooks_test.go | 8 +-- listen_test.go | 4 +- middleware/adaptor/adaptor.go | 4 +- middleware/cache/cache_test.go | 4 +- middleware/compress/compress.go | 2 +- middleware/compress/compress_test.go | 2 +- middleware/encryptcookie/encryptcookie.go | 2 +- middleware/etag/etag_test.go | 4 +- middleware/favicon/favicon_test.go | 10 +-- middleware/idempotency/idempotency_test.go | 2 +- middleware/keyauth/keyauth_test.go | 18 ++--- middleware/logger/logger_test.go | 4 +- middleware/logger/tags.go | 76 +++++++++++----------- middleware/recover/recover_test.go | 4 +- mount_test.go | 28 ++++---- redirect_test.go | 2 +- router_test.go | 14 ++-- 23 files changed, 142 insertions(+), 141 deletions(-) diff --git a/app_test.go b/app_test.go index 18016f1a8f..7cfaa5898b 100644 --- a/app_test.go +++ b/app_test.go @@ -139,7 +139,7 @@ func Test_App_ServerErrorHandler_SmallReadBuffer(t *testing.T) { ) app := New() - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { panic(errors.New("should never called")) }) @@ -160,7 +160,7 @@ func Test_App_Errors(t *testing.T) { BodyLimit: 4, }) - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { return errors.New("hi, i'm an error") }) @@ -236,12 +236,12 @@ func Test_App_CustomConstraint(t *testing.T) { func Test_App_ErrorHandler_Custom(t *testing.T) { t.Parallel() app := New(Config{ - ErrorHandler: func(c Ctx, err error) error { + ErrorHandler: func(c Ctx, _ error) error { return c.Status(200).SendString("hi, i'm an custom error") }, }) - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { return errors.New("hi, i'm an error") }) @@ -271,7 +271,7 @@ func Test_App_ErrorHandler_HandlerStack(t *testing.T) { require.Equal(t, "0: GET error", err.Error()) return errors.New("2: USE error") }) - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { return errors.New("0: GET error") }) @@ -297,7 +297,7 @@ func Test_App_ErrorHandler_RouteStack(t *testing.T) { require.Equal(t, "0: GET error", err.Error()) return errors.New("1: USE error") // [2] call ErrorHandler }) - app.Get("/test", func(c Ctx) error { + app.Get("/test", func(_ Ctx) error { return errors.New("0: GET error") // [1] return to USE }) @@ -1433,7 +1433,7 @@ func Test_Test_Timeout(t *testing.T) { require.NoError(t, err, "app.Test(req)") require.Equal(t, 200, resp.StatusCode, "Status code") - app.Get("timeout", func(c Ctx) error { + app.Get("timeout", func(_ Ctx) error { time.Sleep(200 * time.Millisecond) return nil }) @@ -1633,7 +1633,7 @@ func Test_App_Server(t *testing.T) { func Test_App_Error_In_Fasthttp_Server(t *testing.T) { app := New() - app.config.ErrorHandler = func(c Ctx, err error) error { + app.config.ErrorHandler = func(_ Ctx, _ error) error { return errors.New("fake error") } app.server.GetOnly = true @@ -1731,7 +1731,7 @@ func Test_App_Test_no_timeout_infinitely(t *testing.T) { go func() { defer func() { c <- 0 }() app := New() - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { runtime.Goexit() return nil }) diff --git a/client_test.go b/client_test.go index 57ca0135c5..dba90a2256 100644 --- a/client_test.go +++ b/client_test.go @@ -44,7 +44,7 @@ func Test_Client_Invalid_URL(t *testing.T) { a := Get("http://example.com\r\n\r\nGET /\r\n\r\n") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } _, body, errs := a.String() @@ -86,7 +86,7 @@ func Test_Client_Get(t *testing.T) { for i := 0; i < 5; i++ { a := Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -115,7 +115,7 @@ func Test_Client_Head(t *testing.T) { for i := 0; i < 5; i++ { a := Head("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -151,7 +151,7 @@ func Test_Client_Post(t *testing.T) { a := Post("http://example.com"). Form(args) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -188,7 +188,7 @@ func Test_Client_Put(t *testing.T) { a := Put("http://example.com"). Form(args) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -225,7 +225,7 @@ func Test_Client_Patch(t *testing.T) { a := Patch("http://example.com"). Form(args) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -260,7 +260,7 @@ func Test_Client_Delete(t *testing.T) { a := Delete("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -294,7 +294,7 @@ func Test_Client_UserAgent(t *testing.T) { for i := 0; i < 5; i++ { a := Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -312,7 +312,7 @@ func Test_Client_UserAgent(t *testing.T) { a := c.Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -451,7 +451,7 @@ func Test_Client_Agent_Host(t *testing.T) { require.Equal(t, "1.1.1.1:8080", a.HostClient.Addr) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -560,7 +560,7 @@ func Test_Client_Agent_Custom_Response(t *testing.T) { require.NoError(t, a.Parse()) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.SetResponse(resp). String() @@ -597,7 +597,7 @@ func Test_Client_Agent_Dest(t *testing.T) { a := Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.Dest(dest[:0]).String() @@ -613,7 +613,7 @@ func Test_Client_Agent_Dest(t *testing.T) { a := Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.Dest(dest[:0]).String() @@ -671,11 +671,11 @@ func Test_Client_Agent_RetryIf(t *testing.T) { }() a := Post("http://example.com"). - RetryIf(func(req *Request) bool { + RetryIf(func(_ *Request) bool { return true }) dialsCount := 0 - a.HostClient.Dial = func(addr string) (net.Conn, error) { + a.HostClient.Dial = func(_ string) (net.Conn, error) { dialsCount++ switch dialsCount { case 1: @@ -819,7 +819,7 @@ func Test_Client_Agent_MultipartForm(t *testing.T) { Boundary("myBoundary"). MultipartForm(args) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -900,7 +900,7 @@ func Test_Client_Agent_MultipartForm_SendFiles(t *testing.T) { SendFiles(".github/testdata/index.html", "index", ".github/testdata/index.tmpl"). MultipartForm(nil) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -1010,7 +1010,7 @@ func Test_Client_Agent_Timeout(t *testing.T) { a := Get("http://example.com"). Timeout(time.Millisecond * 50) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } _, body, errs := a.String() @@ -1039,7 +1039,7 @@ func Test_Client_Agent_Reuse(t *testing.T) { a := Get("http://example.com"). Reuse() - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -1152,7 +1152,7 @@ func Test_Client_Agent_MaxRedirectsCount(t *testing.T) { a := Get("http://example.com?foo"). MaxRedirectsCount(1) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() @@ -1166,7 +1166,7 @@ func Test_Client_Agent_MaxRedirectsCount(t *testing.T) { a := Get("http://example.com"). MaxRedirectsCount(1) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } _, body, errs := a.String() @@ -1202,7 +1202,7 @@ func Test_Client_Agent_Struct(t *testing.T) { a := Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } var d data @@ -1220,7 +1220,7 @@ func Test_Client_Agent_Struct(t *testing.T) { errPre := errors.New("pre errors") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } a.errs = append(a.errs, errPre) var d data @@ -1236,7 +1236,7 @@ func Test_Client_Agent_Struct(t *testing.T) { t.Parallel() a := Get("http://example.com/error") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } var d data @@ -1260,7 +1260,7 @@ func Test_Client_Agent_Struct(t *testing.T) { request.SetRequestURI("http://example.com") err := a.Parse() require.NoError(t, err) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } var d data code, body, errs := a.Struct(&d) require.Equal(t, StatusOK, code) @@ -1303,7 +1303,7 @@ func testAgent(t *testing.T, handler Handler, wrapAgent func(agent *Agent), exce wrapAgent(a) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() diff --git a/ctx.go b/ctx.go index 5421674276..93e8948fab 100644 --- a/ctx.go +++ b/ctx.go @@ -294,7 +294,7 @@ func (c *DefaultCtx) ClearCookie(key ...string) { } return } - c.fasthttp.Request.Header.VisitAllCookie(func(k, v []byte) { + c.fasthttp.Request.Header.VisitAllCookie(func(k, _ []byte) { c.fasthttp.Response.Header.DelClientCookieBytes(k) }) } diff --git a/ctx_test.go b/ctx_test.go index 1a7b0bbb98..b91c75d783 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -960,7 +960,7 @@ func Test_Ctx_Format(t *testing.T) { fmts := []ResFmt{} for _, t := range types { t := utils.CopyString(t) - fmts = append(fmts, ResFmt{t, func(c Ctx) error { + fmts = append(fmts, ResFmt{t, func(_ Ctx) error { accepted = t return nil }}) @@ -982,7 +982,7 @@ func Test_Ctx_Format(t *testing.T) { require.NotEqual(t, StatusNotAcceptable, c.Response().StatusCode()) myError := errors.New("this is an error") - err = c.Format(ResFmt{"text/html", func(c Ctx) error { return myError }}) + err = c.Format(ResFmt{"text/html", func(_ Ctx) error { return myError }}) require.ErrorIs(t, err, myError) c.Request().Header.Set(HeaderAccept, "application/json") @@ -2122,7 +2122,7 @@ func Test_Ctx_ClientHelloInfo(t *testing.T) { func Test_Ctx_InvalidMethod(t *testing.T) { t.Parallel() app := New() - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { return nil }) @@ -3399,7 +3399,7 @@ func Test_Ctx_JSON(t *testing.T) { t.Parallel() app := New(Config{ - JSONEncoder: func(v any) ([]byte, error) { + JSONEncoder: func(_ any) ([]byte, error) { return []byte(`["custom","json"]`), nil }, }) @@ -3490,7 +3490,7 @@ func Test_Ctx_JSONP(t *testing.T) { t.Parallel() app := New(Config{ - JSONEncoder: func(v any) ([]byte, error) { + JSONEncoder: func(_ any) ([]byte, error) { return []byte(`["custom","json"]`), nil }, }) @@ -3567,7 +3567,7 @@ func Test_Ctx_XML(t *testing.T) { t.Parallel() app := New(Config{ - XMLEncoder: func(v any) ([]byte, error) { + XMLEncoder: func(_ any) ([]byte, error) { return []byte(`xml`), nil }, }) @@ -3938,11 +3938,11 @@ func Test_Ctx_RestartRoutingWithChangedPath(t *testing.T) { c.Path("/new") return c.RestartRouting() }) - app.Get("/old", func(c Ctx) error { + app.Get("/old", func(_ Ctx) error { executedOldHandler = true return nil }) - app.Get("/new", func(c Ctx) error { + app.Get("/new", func(_ Ctx) error { executedNewHandler = true return nil }) @@ -3958,7 +3958,7 @@ func Test_Ctx_RestartRoutingWithChangedPath(t *testing.T) { func Test_Ctx_RestartRoutingWithChangedPathAndCatchAll(t *testing.T) { t.Parallel() app := New() - app.Get("/new", func(c Ctx) error { + app.Get("/new", func(_ Ctx) error { return nil }) app.Use(func(c Ctx) error { @@ -3966,7 +3966,7 @@ func Test_Ctx_RestartRoutingWithChangedPathAndCatchAll(t *testing.T) { // c.Next() would fail this test as a 404 is returned from the next handler return c.RestartRouting() }) - app.Use(func(c Ctx) error { + app.Use(func(_ Ctx) error { return ErrNotFound }) diff --git a/helpers.go b/helpers.go index e86ed81fe4..fd542c55de 100644 --- a/helpers.go +++ b/helpers.go @@ -53,6 +53,7 @@ func getTLSConfig(ln net.Listener) *tls.Config { if elem := newval.Elem(); elem.Type() != nil { // Cast value to *tls.Config c, ok := elem.Interface().(*tls.Config) + //nolint:revive // We need to check if the type assertion was successful if !ok { panic(fmt.Errorf("failed to type-assert to *tls.Config")) } diff --git a/helpers_test.go b/helpers_test.go index f5b17ca343..dac999309e 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -256,7 +256,7 @@ func Test_Utils_ForEachParameter(t *testing.T) { // go test -v -run=^$ -bench=Benchmark_Utils_ForEachParameter -benchmem -count=4 func Benchmark_Utils_ForEachParameter(b *testing.B) { for n := 0; n < b.N; n++ { - forEachParameter(` ; josua=1 ; vermant="20tw\",bob;sack o" ; version=1; foo=bar; `, func(s1, s2 string) bool { + forEachParameter(` ; josua=1 ; vermant="20tw\",bob;sack o" ; version=1; foo=bar; `, func(_, _ string) bool { return true }) } diff --git a/hooks_test.go b/hooks_test.go index 49d4d34766..91ad87bef7 100644 --- a/hooks_test.go +++ b/hooks_test.go @@ -88,7 +88,7 @@ func Test_Hook_OnName_Error(t *testing.T) { } }() - app.Hooks().OnName(func(r Route) error { + app.Hooks().OnName(func(_ Route) error { return errors.New("unknown error") }) @@ -172,7 +172,7 @@ func Test_Hook_OnGroupName_Error(t *testing.T) { } }() - app.Hooks().OnGroupName(func(g Group) error { + app.Hooks().OnGroupName(func(_ Group) error { return errors.New("unknown error") }) @@ -206,7 +206,7 @@ func Test_Hook_OnListen(t *testing.T) { buf := bytebufferpool.Get() defer bytebufferpool.Put(buf) - app.Hooks().OnListen(func(listenData ListenData) error { + app.Hooks().OnListen(func(_ ListenData) error { _, err := buf.WriteString("ready") require.NoError(t, err) @@ -229,7 +229,7 @@ func Test_Hook_OnListenPrefork(t *testing.T) { buf := bytebufferpool.Get() defer bytebufferpool.Put(buf) - app.Hooks().OnListen(func(listenData ListenData) error { + app.Hooks().OnListen(func(_ ListenData) error { _, err := buf.WriteString("ready") require.NoError(t, err) diff --git a/listen_test.go b/listen_test.go index ffd5379402..d92b9fb396 100644 --- a/listen_test.go +++ b/listen_test.go @@ -78,7 +78,7 @@ func Test_Listen_Graceful_Shutdown(t *testing.T) { time.Sleep(tc.Time) a := Get("http://example.com") - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() require.Equal(t, tc.ExpectedStatusCode, code) @@ -249,7 +249,7 @@ func Test_Listen_TLSConfigFunc(t *testing.T) { require.NoError(t, app.Listen(":0", ListenConfig{ DisableStartupMessage: true, - TLSConfigFunc: func(tlsConfig *tls.Config) { + TLSConfigFunc: func(_ *tls.Config) { callTLSConfig = true }, CertFile: "./.github/testdata/ssl.pem", diff --git a/middleware/adaptor/adaptor.go b/middleware/adaptor/adaptor.go index f3826f2d27..fd31649039 100644 --- a/middleware/adaptor/adaptor.go +++ b/middleware/adaptor/adaptor.go @@ -56,7 +56,7 @@ func CopyContextToFiberContext(context any, requestContext *fasthttp.RequestCtx) CopyContextToFiberContext(reflectValue.Interface(), requestContext) } else if reflectField.Name == "key" { lastKey = reflectValue.Interface() - } else if lastKey != nil && reflectField.Name == "val" { + } else if lastKey != nil && reflectField.Name == "val" { //nolint:revive // We need these checks here requestContext.SetUserValue(lastKey, reflectValue.Interface()) } else { lastKey = nil @@ -69,7 +69,7 @@ func CopyContextToFiberContext(context any, requestContext *fasthttp.RequestCtx) func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler { return func(c fiber.Ctx) error { var next bool - nextHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + nextHandler := http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { next = true // Convert again in case request may modify by middleware c.Request().Header.SetMethod(r.Method) diff --git a/middleware/cache/cache_test.go b/middleware/cache/cache_test.go index cd1fc0e792..1652c0d68e 100644 --- a/middleware/cache/cache_test.go +++ b/middleware/cache/cache_test.go @@ -503,7 +503,7 @@ func Test_CustomExpiration(t *testing.T) { app := fiber.New() var called bool var newCacheTime int - app.Use(New(Config{ExpirationGenerator: func(c fiber.Ctx, cfg *Config) time.Duration { + app.Use(New(Config{ExpirationGenerator: func(c fiber.Ctx, _ *Config) time.Duration { called = true var err error newCacheTime, err = strconv.Atoi(c.GetRespHeader("Cache-Time", "600")) @@ -706,7 +706,7 @@ func Test_CustomCacheHeader(t *testing.T) { // time intervals to maintain strong ascending order of expiration func stableAscendingExpiration() func(c1 fiber.Ctx, c2 *Config) time.Duration { i := 0 - return func(c1 fiber.Ctx, c2 *Config) time.Duration { + return func(_ fiber.Ctx, _ *Config) time.Duration { i++ return time.Hour * time.Duration(i) } diff --git a/middleware/compress/compress.go b/middleware/compress/compress.go index e9e81f73db..00f109148e 100644 --- a/middleware/compress/compress.go +++ b/middleware/compress/compress.go @@ -12,7 +12,7 @@ func New(config ...Config) fiber.Handler { // Setup request handlers var ( - fctx = func(c *fasthttp.RequestCtx) {} + fctx = func(_ *fasthttp.RequestCtx) {} compressor fasthttp.RequestHandler ) diff --git a/middleware/compress/compress_test.go b/middleware/compress/compress_test.go index 25ee7f014f..2d85e790c6 100644 --- a/middleware/compress/compress_test.go +++ b/middleware/compress/compress_test.go @@ -159,7 +159,7 @@ func Test_Compress_Next_Error(t *testing.T) { app.Use(New()) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return errors.New("next error") }) diff --git a/middleware/encryptcookie/encryptcookie.go b/middleware/encryptcookie/encryptcookie.go index a8ce216be2..5faffcc69d 100644 --- a/middleware/encryptcookie/encryptcookie.go +++ b/middleware/encryptcookie/encryptcookie.go @@ -34,7 +34,7 @@ func New(config ...Config) fiber.Handler { err := c.Next() // Encrypt response cookies - c.Response().Header.VisitAllCookie(func(key, value []byte) { + c.Response().Header.VisitAllCookie(func(key, _ []byte) { keyString := string(key) if !isDisabled(keyString, cfg.Except) { cookieValue := fasthttp.Cookie{} diff --git a/middleware/etag/etag_test.go b/middleware/etag/etag_test.go index e3b9f5a96c..9769639cb1 100644 --- a/middleware/etag/etag_test.go +++ b/middleware/etag/etag_test.go @@ -33,7 +33,7 @@ func Test_ETag_SkipError(t *testing.T) { app.Use(New()) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return fiber.ErrForbidden }) @@ -65,7 +65,7 @@ func Test_ETag_NoBody(t *testing.T) { app.Use(New()) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return nil }) diff --git a/middleware/favicon/favicon_test.go b/middleware/favicon/favicon_test.go index 05e89efb27..1a40684a5f 100644 --- a/middleware/favicon/favicon_test.go +++ b/middleware/favicon/favicon_test.go @@ -20,7 +20,7 @@ func Test_Middleware_Favicon(t *testing.T) { app.Use(New()) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return nil }) @@ -66,7 +66,7 @@ func Test_Middleware_Favicon_Found(t *testing.T) { File: "../../.github/testdata/favicon.ico", })) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return nil }) @@ -86,7 +86,7 @@ func Test_Custom_Favicon_URL(t *testing.T) { URL: customURL, })) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return nil }) @@ -108,7 +108,7 @@ func Test_Custom_Favicon_Data(t *testing.T) { Data: data, })) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return nil }) @@ -157,7 +157,7 @@ func Test_Middleware_Favicon_CacheControl(t *testing.T) { func Benchmark_Middleware_Favicon(b *testing.B) { app := fiber.New() app.Use(New()) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return nil }) handler := app.Handler() diff --git a/middleware/idempotency/idempotency_test.go b/middleware/idempotency/idempotency_test.go index f06516fca6..c70e8fd522 100644 --- a/middleware/idempotency/idempotency_test.go +++ b/middleware/idempotency/idempotency_test.go @@ -142,7 +142,7 @@ func Benchmark_Idempotency(b *testing.B) { Lifetime: lifetime, })) - app.Post("/", func(c fiber.Ctx) error { + app.Post("/", func(_ fiber.Ctx) error { return nil }) diff --git a/middleware/keyauth/keyauth_test.go b/middleware/keyauth/keyauth_test.go index 3b1fa01d82..ba795aadf5 100644 --- a/middleware/keyauth/keyauth_test.go +++ b/middleware/keyauth/keyauth_test.go @@ -64,7 +64,7 @@ func TestAuthSources(t *testing.T) { authMiddleware := New(Config{ KeyLookup: authSource + ":" + test.authTokenName, - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == CorrectKey { return true, nil } @@ -141,7 +141,7 @@ func TestMultipleKeyAuth(t *testing.T) { return c.OriginalURL() != "/auth1" }, KeyLookup: "header:key", - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == "password1" { return true, nil } @@ -155,7 +155,7 @@ func TestMultipleKeyAuth(t *testing.T) { return c.OriginalURL() != "/auth2" }, KeyLookup: "header:key", - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == "password2" { return true, nil } @@ -269,10 +269,10 @@ func TestCustomSuccessAndFailureHandlers(t *testing.T) { SuccessHandler: func(c fiber.Ctx) error { return c.Status(fiber.StatusOK).SendString("API key is valid and request was handled by custom success handler") }, - ErrorHandler: func(c fiber.Ctx, err error) error { + ErrorHandler: func(c fiber.Ctx, _ error) error { return c.Status(fiber.StatusUnauthorized).SendString("API key is invalid and request was handled by custom error handler") }, - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == CorrectKey { return true, nil } @@ -281,7 +281,7 @@ func TestCustomSuccessAndFailureHandlers(t *testing.T) { })) // Define a test handler that should not be called - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { t.Error("Test handler should not be called") return nil }) @@ -322,7 +322,7 @@ func TestCustomNextFunc(t *testing.T) { Next: func(c fiber.Ctx) bool { return c.Path() == "/allowed" }, - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == CorrectKey { return true, nil } @@ -382,7 +382,7 @@ func TestAuthSchemeToken(t *testing.T) { app.Use(New(Config{ AuthScheme: "Token", - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == CorrectKey { return true, nil } @@ -418,7 +418,7 @@ func TestAuthSchemeBasic(t *testing.T) { app.Use(New(Config{ KeyLookup: "header:Authorization", AuthScheme: "Basic", - Validator: func(c fiber.Ctx, key string) (bool, error) { + Validator: func(_ fiber.Ctx, key string) (bool, error) { if key == CorrectKey { return true, nil } diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index 4b086011b3..2694e5112d 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -35,7 +35,7 @@ func Test_Logger(t *testing.T) { Output: buf, })) - app.Get("/", func(c fiber.Ctx) error { + app.Get("/", func(_ fiber.Ctx) error { return errors.New("some random error") }) @@ -575,7 +575,7 @@ func Test_CustomTags(t *testing.T) { app.Use(New(Config{ Format: "${custom_tag}", CustomTags: map[string]LogFunc{ - "custom_tag": func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + "custom_tag": func(output Buffer, _ fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(customTag) }, }, diff --git a/middleware/logger/tags.go b/middleware/logger/tags.go index 0d8f3ad3fc..3c383dee7d 100644 --- a/middleware/logger/tags.go +++ b/middleware/logger/tags.go @@ -53,55 +53,55 @@ const ( func createTagMap(cfg *Config) map[string]LogFunc { // Set default tags tagFunctions := map[string]LogFunc{ - TagReferer: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagReferer: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Get(fiber.HeaderReferer)) }, - TagProtocol: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagProtocol: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Protocol()) }, - TagScheme: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagScheme: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Scheme()) }, - TagPort: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagPort: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Port()) }, - TagIP: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagIP: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.IP()) }, - TagIPs: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagIPs: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Get(fiber.HeaderXForwardedFor)) }, - TagHost: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagHost: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Hostname()) }, - TagPath: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagPath: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Path()) }, - TagURL: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagURL: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.OriginalURL()) }, - TagUA: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagUA: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Get(fiber.HeaderUserAgent)) }, - TagBody: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagBody: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.Write(c.Body()) }, - TagBytesReceived: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagBytesReceived: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return appendInt(output, len(c.Request().Body())) }, - TagBytesSent: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagBytesSent: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { if c.Response().Header.ContentLength() < 0 { return appendInt(output, 0) } return appendInt(output, len(c.Response().Body())) }, - TagRoute: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagRoute: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Route().Path) }, - TagResBody: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagResBody: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.Write(c.Response().Body()) }, - TagReqHeaders: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagReqHeaders: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { out := make(map[string][]string, 0) if err := c.Bind().Header(&out); err != nil { return 0, err @@ -113,59 +113,59 @@ func createTagMap(cfg *Config) map[string]LogFunc { } return output.Write([]byte(strings.Join(reqHeaders, "&"))) }, - TagQueryStringParams: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagQueryStringParams: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.Request().URI().QueryArgs().String()) }, - TagBlack: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagBlack: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Black) }, - TagRed: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagRed: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Red) }, - TagGreen: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagGreen: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Green) }, - TagYellow: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagYellow: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Yellow) }, - TagBlue: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagBlue: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Blue) }, - TagMagenta: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagMagenta: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Magenta) }, - TagCyan: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagCyan: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Cyan) }, - TagWhite: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagWhite: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.White) }, - TagReset: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagReset: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { return output.WriteString(c.App().Config().ColorScheme.Reset) }, - TagError: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagError: func(output Buffer, _ fiber.Ctx, data *Data, _ string) (int, error) { if data.ChainErr != nil { return output.WriteString(data.ChainErr.Error()) } return output.WriteString("-") }, - TagReqHeader: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagReqHeader: func(output Buffer, c fiber.Ctx, _ *Data, extraParam string) (int, error) { return output.WriteString(c.Get(extraParam)) }, - TagRespHeader: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagRespHeader: func(output Buffer, c fiber.Ctx, _ *Data, extraParam string) (int, error) { return output.WriteString(c.GetRespHeader(extraParam)) }, - TagQuery: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagQuery: func(output Buffer, c fiber.Ctx, _ *Data, extraParam string) (int, error) { return output.WriteString(fiber.Query[string](c, extraParam)) }, - TagForm: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagForm: func(output Buffer, c fiber.Ctx, _ *Data, extraParam string) (int, error) { return output.WriteString(c.FormValue(extraParam)) }, - TagCookie: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagCookie: func(output Buffer, c fiber.Ctx, _ *Data, extraParam string) (int, error) { return output.WriteString(c.Cookies(extraParam)) }, - TagLocals: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagLocals: func(output Buffer, c fiber.Ctx, _ *Data, extraParam string) (int, error) { switch v := c.Locals(extraParam).(type) { case []byte: return output.Write(v) @@ -177,28 +177,28 @@ func createTagMap(cfg *Config) map[string]LogFunc { return output.WriteString(fmt.Sprintf("%v", v)) } }, - TagStatus: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagStatus: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { if cfg.enableColors { colors := c.App().Config().ColorScheme return output.WriteString(fmt.Sprintf("%s%3d%s", statusColor(c.Response().StatusCode(), colors), c.Response().StatusCode(), colors.Reset)) } return appendInt(output, c.Response().StatusCode()) }, - TagMethod: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagMethod: func(output Buffer, c fiber.Ctx, _ *Data, _ string) (int, error) { if cfg.enableColors { colors := c.App().Config().ColorScheme return output.WriteString(fmt.Sprintf("%s%s%s", methodColor(c.Method(), colors), c.Method(), colors.Reset)) } return output.WriteString(c.Method()) }, - TagPid: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagPid: func(output Buffer, _ fiber.Ctx, data *Data, _ string) (int, error) { return output.WriteString(data.Pid) }, - TagLatency: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagLatency: func(output Buffer, _ fiber.Ctx, data *Data, _ string) (int, error) { latency := data.Stop.Sub(data.Start) return output.WriteString(fmt.Sprintf("%13v", latency)) }, - TagTime: func(output Buffer, c fiber.Ctx, data *Data, extraParam string) (int, error) { + TagTime: func(output Buffer, _ fiber.Ctx, data *Data, _ string) (int, error) { return output.WriteString(data.Timestamp.Load().(string)) //nolint:forcetypeassert // We always store a string in here }, } diff --git a/middleware/recover/recover_test.go b/middleware/recover/recover_test.go index 411c231431..9b5962db90 100644 --- a/middleware/recover/recover_test.go +++ b/middleware/recover/recover_test.go @@ -20,7 +20,7 @@ func Test_Recover(t *testing.T) { app.Use(New()) - app.Get("/panic", func(c fiber.Ctx) error { + app.Get("/panic", func(_ fiber.Ctx) error { panic("Hi, I'm an error!") }) @@ -51,7 +51,7 @@ func Test_Recover_EnableStackTrace(t *testing.T) { EnableStackTrace: true, })) - app.Get("/panic", func(c fiber.Ctx) error { + app.Get("/panic", func(_ fiber.Ctx) error { panic("Hi, I'm an error!") }) diff --git a/mount_test.go b/mount_test.go index 19311febdb..1ec62c0ef6 100644 --- a/mount_test.go +++ b/mount_test.go @@ -237,7 +237,7 @@ func Test_App_ErrorHandler_GroupMount(t *testing.T) { return c.Status(500).SendString("1: custom error") }, }) - micro.Get("/doe", func(c Ctx) error { + micro.Get("/doe", func(_ Ctx) error { return errors.New("0: GET error") }) @@ -257,7 +257,7 @@ func Test_App_ErrorHandler_GroupMountRootLevel(t *testing.T) { return c.Status(500).SendString("1: custom error") }, }) - micro.Get("/john/doe", func(c Ctx) error { + micro.Get("/john/doe", func(_ Ctx) error { return errors.New("0: GET error") }) @@ -290,13 +290,13 @@ func Test_App_Group_Mount(t *testing.T) { func Test_App_UseParentErrorHandler(t *testing.T) { t.Parallel() app := New(Config{ - ErrorHandler: func(ctx Ctx, err error) error { + ErrorHandler: func(ctx Ctx, _ error) error { return ctx.Status(500).SendString("hi, i'm a custom error") }, }) fiber := New() - fiber.Get("/", func(c Ctx) error { + fiber.Get("/", func(_ Ctx) error { return errors.New("something happened") }) @@ -311,11 +311,11 @@ func Test_App_UseMountedErrorHandler(t *testing.T) { app := New() fiber := New(Config{ - ErrorHandler: func(c Ctx, err error) error { + ErrorHandler: func(c Ctx, _ error) error { return c.Status(500).SendString("hi, i'm a custom error") }, }) - fiber.Get("/", func(c Ctx) error { + fiber.Get("/", func(_ Ctx) error { return errors.New("something happened") }) @@ -330,11 +330,11 @@ func Test_App_UseMountedErrorHandlerRootLevel(t *testing.T) { app := New() fiber := New(Config{ - ErrorHandler: func(c Ctx, err error) error { + ErrorHandler: func(c Ctx, _ error) error { return c.Status(500).SendString("hi, i'm a custom error") }, }) - fiber.Get("/api", func(c Ctx) error { + fiber.Get("/api", func(_ Ctx) error { return errors.New("something happened") }) @@ -348,34 +348,34 @@ func Test_App_UseMountedErrorHandlerForBestPrefixMatch(t *testing.T) { t.Parallel() app := New() - tsf := func(c Ctx, err error) error { + tsf := func(c Ctx, _ error) error { return c.Status(200).SendString("hi, i'm a custom sub sub fiber error") } tripleSubFiber := New(Config{ ErrorHandler: tsf, }) - tripleSubFiber.Get("/", func(c Ctx) error { + tripleSubFiber.Get("/", func(_ Ctx) error { return errors.New("something happened") }) - sf := func(c Ctx, err error) error { + sf := func(c Ctx, _ error) error { return c.Status(200).SendString("hi, i'm a custom sub fiber error") } subfiber := New(Config{ ErrorHandler: sf, }) - subfiber.Get("/", func(c Ctx) error { + subfiber.Get("/", func(_ Ctx) error { return errors.New("something happened") }) subfiber.Use("/third", tripleSubFiber) - f := func(c Ctx, err error) error { + f := func(c Ctx, _ error) error { return c.Status(200).SendString("hi, i'm a custom error") } fiber := New(Config{ ErrorHandler: f, }) - fiber.Get("/", func(c Ctx) error { + fiber.Get("/", func(_ Ctx) error { return errors.New("something happened") }) fiber.Use("/sub", subfiber) diff --git a/redirect_test.go b/redirect_test.go index 9b9cd4b204..65f437f190 100644 --- a/redirect_test.go +++ b/redirect_test.go @@ -320,7 +320,7 @@ func Test_Redirect_Request(t *testing.T) { a := Get("http://example.com" + tc.URL) a.Cookie(FlashCookieName, tc.CookieValue) a.MaxRedirectsCount(1) - a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } + a.HostClient.Dial = func(_ string) (net.Conn, error) { return ln.Dial() } code, body, errs := a.String() require.Equal(t, tc.ExpectedStatusCode, code) diff --git a/router_test.go b/router_test.go index 9bd95e0a94..743a58edac 100644 --- a/router_test.go +++ b/router_test.go @@ -318,11 +318,11 @@ func Test_Router_Handler_Catch_Error(t *testing.T) { t.Parallel() app := New() - app.config.ErrorHandler = func(c Ctx, err error) error { + app.config.ErrorHandler = func(_ Ctx, _ error) error { return errors.New("fake error") } - app.Get("/", func(c Ctx) error { + app.Get("/", func(_ Ctx) error { return ErrForbidden }) @@ -494,7 +494,7 @@ func Test_Router_NotFound_HTML_Inject(t *testing.T) { ////////////////////////////////////////////// func registerDummyRoutes(app *App) { - h := func(c Ctx) error { + h := func(_ Ctx) error { return nil } for _, r := range routesFixture.GithubAPI { @@ -680,7 +680,7 @@ func Benchmark_Route_Match(b *testing.B) { Path: "/user/keys/:id", Method: "DELETE", } - route.Handlers = append(route.Handlers, func(c Ctx) error { + route.Handlers = append(route.Handlers, func(_ Ctx) error { return nil }) b.ResetTimer() @@ -709,7 +709,7 @@ func Benchmark_Route_Match_Star(b *testing.B) { Path: "/user/keys/bla", Method: "DELETE", } - route.Handlers = append(route.Handlers, func(c Ctx) error { + route.Handlers = append(route.Handlers, func(_ Ctx) error { return nil }) b.ResetTimer() @@ -739,7 +739,7 @@ func Benchmark_Route_Match_Root(b *testing.B) { Path: "/", Method: "DELETE", } - route.Handlers = append(route.Handlers, func(c Ctx) error { + route.Handlers = append(route.Handlers, func(_ Ctx) error { return nil }) @@ -777,7 +777,7 @@ func Benchmark_Router_Handler_Unescape(b *testing.B) { app := New() app.config.UnescapePath = true registerDummyRoutes(app) - app.Delete("/créer", func(c Ctx) error { + app.Delete("/créer", func(_ Ctx) error { return nil }) From 8d61c3c79ca034b25febdb8aa380ddf65af0d38e Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sun, 11 Feb 2024 15:34:33 -0500 Subject: [PATCH 6/7] Refactor CopyContextToFiberContext --- middleware/adaptor/adaptor.go | 60 +++++++++++++++++++++-------------- 1 file changed, 36 insertions(+), 24 deletions(-) diff --git a/middleware/adaptor/adaptor.go b/middleware/adaptor/adaptor.go index fd31649039..8778709273 100644 --- a/middleware/adaptor/adaptor.go +++ b/middleware/adaptor/adaptor.go @@ -39,30 +39,42 @@ func ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error) { // CopyContextToFiberContext copies the values of context.Context to a fasthttp.RequestCtx func CopyContextToFiberContext(context any, requestContext *fasthttp.RequestCtx) { - contextValues := reflect.ValueOf(context).Elem() - contextKeys := reflect.TypeOf(context).Elem() - if contextKeys.Kind() == reflect.Struct { - var lastKey any - for i := 0; i < contextValues.NumField(); i++ { - reflectValue := contextValues.Field(i) - /* #nosec */ - reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem() - - reflectField := contextKeys.Field(i) - - if reflectField.Name == "noCopy" { - break - } else if reflectField.Name == "Context" { - CopyContextToFiberContext(reflectValue.Interface(), requestContext) - } else if reflectField.Name == "key" { - lastKey = reflectValue.Interface() - } else if lastKey != nil && reflectField.Name == "val" { //nolint:revive // We need these checks here - requestContext.SetUserValue(lastKey, reflectValue.Interface()) - } else { - lastKey = nil - } - } - } + contextValue := reflect.ValueOf(context).Elem() + contextType := reflect.TypeOf(context).Elem() + + if contextType.Kind() != reflect.Struct { + return + } + + var lastKey any + for i := 0; i < contextValue.NumField(); i++ { + field := contextValue.Field(i) + fieldType := contextType.Field(i) + + // Skip unexported fields or the special "noCopy" field. + if fieldType.PkgPath != "" || fieldType.Name == "noCopy" { + continue + } + + // Use unsafe to bypass restrictions (like unexported fields). + field = reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem() + + switch fieldType.Name { + case "Context": + // Recursively copy nested Context values. + CopyContextToFiberContext(field.Interface(), requestContext) + case "key": + // Remember the last key to pair it with a value later. + lastKey = field.Interface() + case "val": + if lastKey != nil { + // If there's a key waiting for a value, set it in the request context. + requestContext.SetUserValue(lastKey, field.Interface()) + // Reset the lastKey to ensure pairs are matched correctly. + lastKey = nil + } + } + } } // HTTPMiddleware wraps net/http middleware to fiber middleware From 9cc6a30f4e2dde86022315f1323243d1939eafb7 Mon Sep 17 00:00:00 2001 From: Juan Calderon-Perez <835733+gaby@users.noreply.github.com> Date: Sun, 11 Feb 2024 15:41:23 -0500 Subject: [PATCH 7/7] Update adaptor.go --- middleware/adaptor/adaptor.go | 74 +++++++++++++++++------------------ 1 file changed, 37 insertions(+), 37 deletions(-) diff --git a/middleware/adaptor/adaptor.go b/middleware/adaptor/adaptor.go index 8778709273..5b666e3caa 100644 --- a/middleware/adaptor/adaptor.go +++ b/middleware/adaptor/adaptor.go @@ -37,44 +37,44 @@ func ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error) { return &req, nil } -// CopyContextToFiberContext copies the values of context.Context to a fasthttp.RequestCtx +// CopyContextToFiberContext copies the values of context.Context to a fasthttp.RequestCtx. func CopyContextToFiberContext(context any, requestContext *fasthttp.RequestCtx) { - contextValue := reflect.ValueOf(context).Elem() - contextType := reflect.TypeOf(context).Elem() - - if contextType.Kind() != reflect.Struct { - return - } - - var lastKey any - for i := 0; i < contextValue.NumField(); i++ { - field := contextValue.Field(i) - fieldType := contextType.Field(i) - - // Skip unexported fields or the special "noCopy" field. - if fieldType.PkgPath != "" || fieldType.Name == "noCopy" { - continue - } - - // Use unsafe to bypass restrictions (like unexported fields). - field = reflect.NewAt(field.Type(), unsafe.Pointer(field.UnsafeAddr())).Elem() - - switch fieldType.Name { - case "Context": - // Recursively copy nested Context values. - CopyContextToFiberContext(field.Interface(), requestContext) - case "key": - // Remember the last key to pair it with a value later. - lastKey = field.Interface() - case "val": - if lastKey != nil { - // If there's a key waiting for a value, set it in the request context. - requestContext.SetUserValue(lastKey, field.Interface()) - // Reset the lastKey to ensure pairs are matched correctly. - lastKey = nil - } - } - } + contextValues := reflect.ValueOf(context).Elem() + contextKeys := reflect.TypeOf(context).Elem() + + if contextKeys.Kind() != reflect.Struct { + return + } + + var lastKey any + for i := 0; i < contextValues.NumField(); i++ { + reflectValue := contextValues.Field(i) + reflectField := contextKeys.Field(i) + + if reflectField.Name == "noCopy" { + break + } + + // Use unsafe to access potentially unexported fields. + if reflectValue.CanAddr() { + /* #nosec */ + reflectValue = reflect.NewAt(reflectValue.Type(), unsafe.Pointer(reflectValue.UnsafeAddr())).Elem() + } + + switch reflectField.Name { + case "Context": + CopyContextToFiberContext(reflectValue.Interface(), requestContext) + case "key": + lastKey = reflectValue.Interface() + case "val": + if lastKey != nil { + requestContext.SetUserValue(lastKey, reflectValue.Interface()) + lastKey = nil // Reset lastKey after setting the value + } + default: + continue + } + } } // HTTPMiddleware wraps net/http middleware to fiber middleware