diff --git a/app.go b/app.go index aeec04888f..74f92c6333 100644 --- a/app.go +++ b/app.go @@ -897,7 +897,7 @@ func (app *App) init() *App { } // ErrorHandler is the application's method in charge of finding the -// appropiate handler for the given request. It searches any mounted +// appropriate handler for the given request. It searches any mounted // sub fibers by their prefixes and if it finds a match, it uses that // error handler. Otherwise it uses the configured error handler for // the app, which if not set is the DefaultErrorHandler. diff --git a/app_test.go b/app_test.go index 46304ef265..b244cc7cc0 100644 --- a/app_test.go +++ b/app_test.go @@ -34,6 +34,8 @@ var testEmptyHandler = func(c *Ctx) error { } func testStatus200(t *testing.T, app *App, url string, method string) { + t.Helper() + req := httptest.NewRequest(method, url, nil) resp, err := app.Test(req) @@ -447,7 +449,6 @@ func Test_App_Chaining(t *testing.T) { resp, err = app.Test(req) utils.AssertEqual(t, nil, err, "app.Test(req)") utils.AssertEqual(t, 203, resp.StatusCode, "Status code") - } func Test_App_Order(t *testing.T) { @@ -478,8 +479,9 @@ func Test_App_Order(t *testing.T) { utils.AssertEqual(t, nil, err) utils.AssertEqual(t, "123", string(body)) } + func Test_App_Methods(t *testing.T) { - var dummyHandler = testEmptyHandler + dummyHandler := testEmptyHandler app := New() @@ -515,7 +517,6 @@ func Test_App_Methods(t *testing.T) { app.Use("/:john?/:doe?", dummyHandler) testStatus200(t, app, "/john/doe", MethodGet) - } func Test_App_New(t *testing.T) { @@ -652,7 +653,6 @@ func Test_App_Static_Group(t *testing.T) { utils.AssertEqual(t, 200, resp.StatusCode, "Status code") utils.AssertEqual(t, false, resp.Header.Get(HeaderContentLength) == "") utils.AssertEqual(t, MIMETextHTMLCharsetUTF8, resp.Header.Get(HeaderContentType)) - } func Test_App_Static_Wildcard(t *testing.T) { @@ -670,7 +670,6 @@ func Test_App_Static_Wildcard(t *testing.T) { body, err := ioutil.ReadAll(resp.Body) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, true, strings.Contains(string(body), "Test file")) - } func Test_App_Static_Prefix_Wildcard(t *testing.T) { @@ -887,7 +886,7 @@ func Test_App_Group_Mount(t *testing.T) { } func Test_App_Group(t *testing.T) { - var dummyHandler = testEmptyHandler + dummyHandler := testEmptyHandler app := New() @@ -937,18 +936,18 @@ func Test_App_Group(t *testing.T) { resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", nil)) utils.AssertEqual(t, nil, err, "app.Test(req)") utils.AssertEqual(t, 200, resp.StatusCode, "Status code") - //utils.AssertEqual(t, "/test/v1", resp.Header.Get("Location"), "Location") + // utils.AssertEqual(t, "/test/v1", resp.Header.Get("Location"), "Location") api.Get("/users", dummyHandler) resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", nil)) utils.AssertEqual(t, nil, err, "app.Test(req)") utils.AssertEqual(t, 200, resp.StatusCode, "Status code") - //utils.AssertEqual(t, "/test/v1/users", resp.Header.Get("Location"), "Location") + // utils.AssertEqual(t, "/test/v1/users", resp.Header.Get("Location"), "Location") } func Test_App_Deep_Group(t *testing.T) { runThroughCount := 0 - var dummyHandler = func(c *Ctx) error { + dummyHandler := func(c *Ctx) error { runThroughCount++ return c.Next() } diff --git a/client_test.go b/client_test.go index 209cbb8530..117d12e20b 100644 --- a/client_test.go +++ b/client_test.go @@ -307,7 +307,6 @@ func Test_Client_Agent_Set_Or_Add_Headers(t *testing.T) { AddBytesKV([]byte("k1"), []byte("v33")). SetBytesKV([]byte("k2"), []byte("v2")). Add("k2", "v22") - } testAgent(t, handler, wrapAgent, "K1v1K1v11K1v22K1v33K2v2K2v22") @@ -700,7 +699,7 @@ func Test_Client_Agent_MultipartForm_SendFiles(t *testing.T) { fh1, err := c.FormFile("field1") utils.AssertEqual(t, nil, err) utils.AssertEqual(t, fh1.Filename, "name") - buf := make([]byte, fh1.Size, fh1.Size) + buf := make([]byte, fh1.Size) f, err := fh1.Open() utils.AssertEqual(t, nil, err) defer func() { _ = f.Close() }() @@ -746,13 +745,15 @@ func Test_Client_Agent_MultipartForm_SendFiles(t *testing.T) { } func checkFormFile(t *testing.T, fh *multipart.FileHeader, filename string) { + t.Helper() + basename := filepath.Base(filename) utils.AssertEqual(t, fh.Filename, basename) b1, err := ioutil.ReadFile(filename) utils.AssertEqual(t, nil, err) - b2 := make([]byte, fh.Size, fh.Size) + b2 := make([]byte, fh.Size) f, err := fh.Open() utils.AssertEqual(t, nil, err) defer func() { _ = f.Close() }() @@ -998,6 +999,8 @@ func Test_Client_Agent_Struct(t *testing.T) { go func() { utils.AssertEqual(t, nil, app.Listener(ln)) }() t.Run("success", func(t *testing.T) { + t.Parallel() + a := Get("http://example.com") a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } @@ -1013,6 +1016,7 @@ func Test_Client_Agent_Struct(t *testing.T) { }) t.Run("pre error", func(t *testing.T) { + t.Parallel() a := Get("http://example.com") a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() } diff --git a/ctx.go b/ctx.go index b612fc40a7..acd18494d5 100644 --- a/ctx.go +++ b/ctx.go @@ -301,7 +301,7 @@ func SetParserDecoder(parserConfig ParserConfig) { } func decoderBuilder(parserConfig ParserConfig) interface{} { - var decoder = schema.NewDecoder() + decoder := schema.NewDecoder() decoder.IgnoreUnknownKeys(parserConfig.IgnoreUnknownKeys) if parserConfig.SetAliasTag != "" { decoder.SetAliasTag(parserConfig.SetAliasTag) @@ -518,8 +518,8 @@ func (c *Ctx) FormValue(key string, defaultValue ...string) string { // https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33 func (c *Ctx) Fresh() bool { // fields - var modifiedSince = c.Get(HeaderIfModifiedSince) - var noneMatch = c.Get(HeaderIfNoneMatch) + modifiedSince := c.Get(HeaderIfModifiedSince) + noneMatch := c.Get(HeaderIfNoneMatch) // unconditional request if modifiedSince == "" && noneMatch == "" { @@ -536,7 +536,7 @@ func (c *Ctx) Fresh() bool { // if-none-match if noneMatch != "" && noneMatch != "*" { - var etag = c.app.getString(c.fasthttp.Response.Header.Peek(HeaderETag)) + etag := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderETag)) if etag == "" { return false } @@ -545,7 +545,7 @@ func (c *Ctx) Fresh() bool { } if modifiedSince != "" { - var lastModified = c.app.getString(c.fasthttp.Response.Header.Peek(HeaderLastModified)) + lastModified := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderLastModified)) if lastModified != "" { lastModifiedTime, err := http.ParseTime(lastModified) if err != nil { @@ -576,7 +576,6 @@ func (c *Ctx) Get(key string, defaultValue ...string) string { // Make copies or use the Immutable setting instead. func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string { return defaultString(c.app.getString(c.fasthttp.Response.Header.Peek(key)), defaultValue) - } // Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header. @@ -662,7 +661,6 @@ func (c *Ctx) JSON(data interface{}) error { // By default, the callback name is simply callback. func (c *Ctx) JSONP(data interface{}, callback ...string) error { raw, err := json.Marshal(data) - if err != nil { return err } @@ -856,7 +854,7 @@ func (c *Ctx) Query(key string, defaultValue ...string) string { // QueryParser binds the query string to a struct. func (c *Ctx) QueryParser(out interface{}) error { // Get decoder from pool - var decoder = decoderPool.Get().(*schema.Decoder) + decoder := decoderPool.Get().(*schema.Decoder) defer decoderPool.Put(decoder) // Set correct alias tag @@ -1063,9 +1061,11 @@ func (c *Ctx) Send(body []byte) error { return nil } -var sendFileOnce sync.Once -var sendFileFS *fasthttp.FS -var sendFileHandler fasthttp.RequestHandler +var ( + sendFileOnce sync.Once + sendFileFS *fasthttp.FS + sendFileHandler fasthttp.RequestHandler +) // SendFile transfers the file from the given path. // The file is not compressed by default, enable this by passing a 'true' argument @@ -1094,7 +1094,7 @@ func (c *Ctx) SendFile(file string, compress ...bool) error { // Keep original path for mutable params c.pathOriginal = utils.CopyString(c.pathOriginal) // Disable compression - if len(compress) <= 0 || !compress[0] { + if len(compress) == 0 || !compress[0] { // https://github.com/valyala/fasthttp/blob/master/fs.go#L46 c.fasthttp.Request.Header.Del(HeaderAcceptEncoding) } diff --git a/ctx_test.go b/ctx_test.go index 9cf4918208..e1bec56646 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -22,7 +22,6 @@ import ( "reflect" "strconv" "strings" - "sync" "testing" "text/template" "time" @@ -403,7 +402,7 @@ func Test_Ctx_BodyParser(t *testing.T) { func Test_Ctx_BodyParser_WithSetParserDecoder(t *testing.T) { type CustomTime time.Time - var timeConverter = func(value string) reflect.Value { + timeConverter := func(value string) reflect.Value { if v, err := time.Parse("2006-01-02", value); err == nil { return reflect.ValueOf(v) } @@ -567,7 +566,6 @@ func Test_Ctx_UserContext(t *testing.T) { t.Run("Nil_Context", func(t *testing.T) { ctx := c.UserContext() utils.AssertEqual(t, ctx, context.Background()) - }) t.Run("ValueContext", func(t *testing.T) { testKey := "Test Key" @@ -634,12 +632,12 @@ func Test_Ctx_Cookie(t *testing.T) { expire := time.Now().Add(24 * time.Hour) var dst []byte dst = expire.In(time.UTC).AppendFormat(dst, time.RFC1123) - httpdate := strings.Replace(string(dst), "UTC", "GMT", -1) + httpdate := strings.ReplaceAll(string(dst), "UTC", "GMT") cookie := &Cookie{ Name: "username", Value: "john", Expires: expire, - //SameSite: CookieSameSiteStrictMode, // default is "lax" + // SameSite: CookieSameSiteStrictMode, // default is "lax" } c.Cookie(cookie) expect := "username=john; expires=" + httpdate + "; path=/; SameSite=Lax" @@ -1233,7 +1231,6 @@ func Benchmark_Ctx_MultipartForm(b *testing.B) { for n := 0; n < b.N; n++ { h(c) } - } // go test -run Test_Ctx_OriginalURL @@ -1452,19 +1449,19 @@ func Test_Ctx_Range(t *testing.T) { err error ) - result, err = c.Range(1000) + _, err = c.Range(1000) utils.AssertEqual(t, true, err != nil) c.Request().Header.Set(HeaderRange, "bytes=500") - result, err = c.Range(1000) + _, err = c.Range(1000) utils.AssertEqual(t, true, err != nil) c.Request().Header.Set(HeaderRange, "bytes=500=") - result, err = c.Range(1000) + _, err = c.Range(1000) utils.AssertEqual(t, true, err != nil) c.Request().Header.Set(HeaderRange, "bytes=500-300") - result, err = c.Range(1000) + _, err = c.Range(1000) utils.AssertEqual(t, true, err != nil) testRange := func(header string, start, end int) { @@ -1827,7 +1824,7 @@ func Benchmark_Ctx_JSONP(b *testing.B) { Name: "Grame", Age: 20, } - var callback = "emit" + callback := "emit" var err error b.ReportAllocs() b.ResetTimer() @@ -1951,7 +1948,6 @@ func Test_Ctx_Render(t *testing.T) { } type testTemplateEngine struct { - mu sync.Mutex templates *template.Template } @@ -2077,7 +2073,7 @@ func Benchmark_Ctx_Send(b *testing.B) { app := New() c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) - var byt = []byte("Hello, World!") + byt := []byte("Hello, World!") b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { @@ -2158,7 +2154,6 @@ func Test_Ctx_Set_Splitter(t *testing.T) { c.Set("Location", "foo\nSet-Cookie:%20SESSIONID=MaliciousValue\n") h = string(c.Response().Header.Peek("Location")) utils.AssertEqual(t, false, strings.Contains(h, "\n"), h) - } // go test -v -run=^$ -bench=Benchmark_Ctx_Set -benchmem -count=4 @@ -2166,7 +2161,7 @@ func Benchmark_Ctx_Set(b *testing.B) { app := New() c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) - var val = "1431-15132-3423" + val := "1431-15132-3423" b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { @@ -2272,7 +2267,7 @@ func Benchmark_Ctx_Write(b *testing.B) { app := New() c := app.AcquireCtx(&fasthttp.RequestCtx{}) defer app.ReleaseCtx(c) - var byt = []byte("Hello, World!") + byt := []byte("Hello, World!") b.ReportAllocs() b.ResetTimer() for n := 0; n < b.N; n++ { @@ -2400,7 +2395,7 @@ func Test_Ctx_QueryParser(t *testing.T) { func Test_Ctx_QueryParser_WithSetParserDecoder(t *testing.T) { type NonRFCTime time.Time - var NonRFCConverter = func(value string) reflect.Value { + NonRFCConverter := func(value string) reflect.Value { if v, err := time.Parse("2006-01-02", value); err == nil { return reflect.ValueOf(v) } @@ -2743,7 +2738,6 @@ func TestCtx_ParamsInt(t *testing.T) { app.Test(httptest.NewRequest(MethodGet, "/testnoint/xd", nil)) app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", nil)) app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", nil)) - } // go test -run Test_Ctx_GetRespHeader diff --git a/group.go b/group.go index f0d5217dfa..241545fd00 100644 --- a/group.go +++ b/group.go @@ -48,7 +48,7 @@ func (grp *Group) Mount(prefix string, fiber *App) Router { // // This method will match all HTTP verbs: GET, POST, PUT, HEAD etc... func (grp *Group) Use(args ...interface{}) Router { - var prefix = "" + prefix := "" var handlers []Handler for i := 0; i < len(args); i++ { switch arg := args[i].(type) { diff --git a/helpers.go b/helpers.go index 00998503e5..691b0e0782 100644 --- a/helpers.go +++ b/helpers.go @@ -122,7 +122,7 @@ func methodExist(ctx *Ctx) (exist bool) { } // Get stack length lenr := len(tree) - 1 - //Loop over the route stack starting from previous index + // Loop over the route stack starting from previous index for ctx.indexRoute < lenr { // Increment route index ctx.indexRoute++ @@ -182,7 +182,7 @@ func setETag(c *Ctx, weak bool) { } body := c.fasthttp.Response.Body() // Skips ETag if no response body is present - if len(body) <= 0 { + if len(body) == 0 { return } // Get ETag header from request @@ -344,6 +344,7 @@ type testAddr string func (a testAddr) Network() string { return string(a) } + func (a testAddr) String() string { return string(a) } @@ -689,7 +690,7 @@ const ( NetworkTCP6 = "tcp6" ) -//Compression types +// Compression types const ( StrGzip = "gzip" StrBr = "br" diff --git a/helpers_test.go b/helpers_test.go index 4597e37f4c..ce4870b34a 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -333,7 +333,6 @@ func Benchmark_SlashRecognition(b *testing.B) { c := int32(slashDelimiter) for i := 0; i < b.N; i++ { result = IndexRune(search, c) - } utils.AssertEqual(b, true, result) }) diff --git a/middleware/basicauth/config.go b/middleware/basicauth/config.go index 952933c1ff..3845e91538 100644 --- a/middleware/basicauth/config.go +++ b/middleware/basicauth/config.go @@ -2,6 +2,7 @@ package basicauth import ( "crypto/subtle" + "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/utils" ) diff --git a/middleware/cache/cache_test.go b/middleware/cache/cache_test.go index 73ee746947..2cdf995a7a 100644 --- a/middleware/cache/cache_test.go +++ b/middleware/cache/cache_test.go @@ -278,7 +278,6 @@ func Test_CustomKey(t *testing.T) { _, err := app.Test(req) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, true, called) - } func Test_CacheHeader(t *testing.T) { diff --git a/middleware/cache/manager.go b/middleware/cache/manager.go index dbeccf7076..08874f38ac 100644 --- a/middleware/cache/manager.go +++ b/middleware/cache/manager.go @@ -79,7 +79,6 @@ func (m *manager) get(key string) (it *item) { it = m.acquire() } return - } // get raw data from storage or memory diff --git a/middleware/cors/cors.go b/middleware/cors/cors.go index 60a93fa4fa..5640cc3f2d 100644 --- a/middleware/cors/cors.go +++ b/middleware/cors/cors.go @@ -90,12 +90,12 @@ func New(config ...Config) fiber.Handler { } // Convert string to slice - allowOrigins := strings.Split(strings.Replace(cfg.AllowOrigins, " ", "", -1), ",") + allowOrigins := strings.Split(strings.ReplaceAll(cfg.AllowOrigins, " ", ""), ",") // Strip white spaces - allowMethods := strings.Replace(cfg.AllowMethods, " ", "", -1) - allowHeaders := strings.Replace(cfg.AllowHeaders, " ", "", -1) - exposeHeaders := strings.Replace(cfg.ExposeHeaders, " ", "", -1) + allowMethods := strings.ReplaceAll(cfg.AllowMethods, " ", "") + allowHeaders := strings.ReplaceAll(cfg.AllowHeaders, " ", "") + exposeHeaders := strings.ReplaceAll(cfg.ExposeHeaders, " ", "") // Convert int to string maxAge := strconv.Itoa(cfg.MaxAge) diff --git a/middleware/cors/cors_test.go b/middleware/cors/cors_test.go index 2722662e11..fc6d1e53e8 100644 --- a/middleware/cors/cors_test.go +++ b/middleware/cors/cors_test.go @@ -24,6 +24,8 @@ func Test_CORS_Empty_Config(t *testing.T) { } func testDefaultOrEmptyConfig(t *testing.T, app *fiber.App) { + t.Helper() + h := app.Handler() // Test default GET response headers @@ -82,7 +84,6 @@ func Test_CORS_Wildcard(t *testing.T) { utils.AssertEqual(t, "true", 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_Subdomain diff --git a/middleware/csrf/csrf_test.go b/middleware/csrf/csrf_test.go index 364a05b8fe..65b302dbe8 100644 --- a/middleware/csrf/csrf_test.go +++ b/middleware/csrf/csrf_test.go @@ -28,8 +28,6 @@ func Test_CSRF(t *testing.T) { // Generate CSRF token ctx.Request.Header.SetMethod(method) h(ctx) - token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie)) - token = strings.Split(strings.Split(token, ";")[0], "=")[1] // Without CSRF cookie ctx.Request.Reset() @@ -51,7 +49,7 @@ func Test_CSRF(t *testing.T) { ctx.Response.Reset() ctx.Request.Header.SetMethod(method) h(ctx) - token = string(ctx.Response.Header.Peek(fiber.HeaderSetCookie)) + token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie)) token = strings.Split(strings.Split(token, ";")[0], "=")[1] ctx.Request.Reset() diff --git a/middleware/csrf/extractors.go b/middleware/csrf/extractors.go index 7d32dd8d3e..2b577b1233 100644 --- a/middleware/csrf/extractors.go +++ b/middleware/csrf/extractors.go @@ -2,6 +2,7 @@ package csrf import ( "errors" + "github.com/gofiber/fiber/v2" ) diff --git a/middleware/csrf/manager.go b/middleware/csrf/manager.go index f7683c0f61..dd70c2ed1c 100644 --- a/middleware/csrf/manager.go +++ b/middleware/csrf/manager.go @@ -12,8 +12,7 @@ import ( // msgp -file="manager.go" -o="manager_msgp.go" -tests=false -unexported // don't forget to replace the msgp import path to: // "github.com/gofiber/fiber/v2/internal/msgp" -type item struct { -} +type item struct{} //msgp:ignore manager type manager struct { diff --git a/middleware/etag/etag.go b/middleware/etag/etag.go index 61d3f6f5a5..153f84d838 100644 --- a/middleware/etag/etag.go +++ b/middleware/etag/etag.go @@ -8,15 +8,17 @@ import ( "github.com/gofiber/fiber/v2/internal/bytebufferpool" ) -var normalizedHeaderETag = []byte("Etag") -var weakPrefix = []byte("W/") +var ( + normalizedHeaderETag = []byte("Etag") + weakPrefix = []byte("W/") +) // New creates a new middleware handler func New(config ...Config) fiber.Handler { // Set default config cfg := configDefault(config...) - var crc32q = crc32.MakeTable(0xD5828281) + crc32q := crc32.MakeTable(0xD5828281) // Return new handler return func(c *fiber.Ctx) (err error) { @@ -36,7 +38,7 @@ func New(config ...Config) fiber.Handler { } body := c.Response().Body() // Skips ETag if no response body is present - if len(body) <= 0 { + if len(body) == 0 { return } // Skip ETag if header is already present diff --git a/middleware/etag/etag_test.go b/middleware/etag/etag_test.go index b0e4bc7675..c5765fc8ba 100644 --- a/middleware/etag/etag_test.go +++ b/middleware/etag/etag_test.go @@ -84,6 +84,8 @@ func Test_ETag_NewEtag(t *testing.T) { } func testETagNewEtag(t *testing.T, headerIfNoneMatch, matched bool) { + t.Helper() + app := fiber.New() app.Use(New()) @@ -132,6 +134,8 @@ func Test_ETag_WeakEtag(t *testing.T) { } func testETagWeakEtag(t *testing.T, headerIfNoneMatch, matched bool) { + t.Helper() + app := fiber.New() app.Use(New(Config{Weak: true})) @@ -180,6 +184,8 @@ func Test_ETag_CustomEtag(t *testing.T) { } func testETagCustomEtag(t *testing.T, headerIfNoneMatch, matched bool) { + t.Helper() + app := fiber.New() app.Use(New()) diff --git a/middleware/favicon/favicon.go b/middleware/favicon/favicon.go index 924f7e6139..c2d12b32a3 100644 --- a/middleware/favicon/favicon.go +++ b/middleware/favicon/favicon.go @@ -82,10 +82,8 @@ func New(config ...Config) fiber.Handler { if icon, err = ioutil.ReadAll(f); err != nil { panic(err) } - } else { - if icon, err = ioutil.ReadFile(cfg.File); err != nil { - panic(err) - } + } else if icon, err = ioutil.ReadFile(cfg.File); err != nil { + panic(err) } iconLen = strconv.Itoa(len(icon)) diff --git a/middleware/favicon/favicon_test.go b/middleware/favicon/favicon_test.go index 17f43b67b0..bcd6a0a849 100644 --- a/middleware/favicon/favicon_test.go +++ b/middleware/favicon/favicon_test.go @@ -78,8 +78,7 @@ func Test_Middleware_Favicon_Found(t *testing.T) { // mockFS wraps local filesystem for the purposes of // Test_Middleware_Favicon_FileSystem located below // TODO use os.Dir if fiber upgrades to 1.16 -type mockFS struct { -} +type mockFS struct{} func (m mockFS) Open(name string) (http.File, error) { if name == "/" { diff --git a/middleware/filesystem/filesystem.go b/middleware/filesystem/filesystem.go index 73b9793eca..aca5a1bf55 100644 --- a/middleware/filesystem/filesystem.go +++ b/middleware/filesystem/filesystem.go @@ -95,7 +95,7 @@ func New(config ...Config) fiber.Handler { var once sync.Once var prefix string - var cacheControlStr = "public, max-age=" + strconv.Itoa(cfg.MaxAge) + cacheControlStr := "public, max-age=" + strconv.Itoa(cfg.MaxAge) // Return new handler return func(c *fiber.Ctx) (err error) { diff --git a/middleware/filesystem/filesystem_test.go b/middleware/filesystem/filesystem_test.go index 0605fc151d..454811e71a 100644 --- a/middleware/filesystem/filesystem_test.go +++ b/middleware/filesystem/filesystem_test.go @@ -33,7 +33,7 @@ func Test_FileSystem(t *testing.T) { })) app.Use("/prefix", New(Config{ - Root: http.Dir("../../.github/testdata/fs"), + Root: http.Dir("../../.github/testdata/fs"), PathPrefix: "img", })) @@ -108,9 +108,9 @@ func Test_FileSystem(t *testing.T) { contentType: "text/html", }, { - name: "PathPrefix should be applied", - url: "/prefix/fiber.png", - statusCode: 200, + name: "PathPrefix should be applied", + url: "/prefix/fiber.png", + statusCode: 200, contentType: "image/png", }, } diff --git a/middleware/limiter/limited_fixed.go b/middleware/limiter/limited_fixed.go index 2de7ffacd6..7936ca7a31 100644 --- a/middleware/limiter/limited_fixed.go +++ b/middleware/limiter/limited_fixed.go @@ -54,7 +54,6 @@ func (FixedWindow) New(cfg Config) fiber.Handler { // Set expiration if entry does not exist if e.exp == 0 { e.exp = ts + expiration - } else if ts >= e.exp { // Check if entry is expired e.currHits = 0 diff --git a/middleware/limiter/limited_sliding.go b/middleware/limiter/limited_sliding.go index f198d35384..5f6ed434d6 100644 --- a/middleware/limiter/limited_sliding.go +++ b/middleware/limiter/limited_sliding.go @@ -54,7 +54,6 @@ func (SlidingWindow) New(cfg Config) fiber.Handler { // Set expiration if entry does not exist if e.exp == 0 { e.exp = ts + expiration - } else if ts >= e.exp { // The entry has expired, handle the expiration. // Set the prevHits to the current hits and reset the hits to 0. diff --git a/middleware/limiter/limiter_test.go b/middleware/limiter/limiter_test.go index fc3daddeb7..2a3e3d6fa0 100644 --- a/middleware/limiter/limiter_test.go +++ b/middleware/limiter/limiter_test.go @@ -62,7 +62,6 @@ func Test_Limiter_Concurrency_Store(t *testing.T) { // go test -run Test_Limiter_Concurrency -race -v func Test_Limiter_Concurrency(t *testing.T) { - // Test concurrency using a default store app := fiber.New() @@ -104,12 +103,10 @@ func Test_Limiter_Concurrency(t *testing.T) { resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/", nil)) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, 200, resp.StatusCode) - } // go test -run Test_Limiter_No_Skip_Choices -v func Test_Limiter_No_Skip_Choices(t *testing.T) { - app := fiber.New() app.Use(New(Config{ @@ -137,12 +134,10 @@ func Test_Limiter_No_Skip_Choices(t *testing.T) { resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/success", nil)) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, 429, resp.StatusCode) - } // go test -run Test_Limiter_Skip_Failed_Requests -v func Test_Limiter_Skip_Failed_Requests(t *testing.T) { - app := fiber.New() app.Use(New(Config{ @@ -175,12 +170,10 @@ func Test_Limiter_Skip_Failed_Requests(t *testing.T) { resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/success", nil)) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, 200, resp.StatusCode) - } // go test -run Test_Limiter_Skip_Successful_Requests -v func Test_Limiter_Skip_Successful_Requests(t *testing.T) { - // Test concurrency using a default store app := fiber.New() @@ -215,7 +208,6 @@ func Test_Limiter_Skip_Successful_Requests(t *testing.T) { resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/fail", nil)) utils.AssertEqual(t, nil, err) utils.AssertEqual(t, 400, resp.StatusCode) - } // go test -v -run=^$ -bench=Benchmark_Limiter_Custom_Store -benchmem -count=4 diff --git a/middleware/limiter/manager.go b/middleware/limiter/manager.go index ed2fa9d726..68a785a7c2 100644 --- a/middleware/limiter/manager.go +++ b/middleware/limiter/manager.go @@ -72,7 +72,6 @@ func (m *manager) get(key string) (it *item) { it = m.acquire() } return - } // get raw data from storage or memory diff --git a/middleware/logger/config.go b/middleware/logger/config.go index 0ab75d6fd5..04e39dcd09 100644 --- a/middleware/logger/config.go +++ b/middleware/logger/config.go @@ -59,7 +59,7 @@ var ConfigDefault = Config{ // Function to check if the logger format is compatible for coloring func validCustomFormat(format string) bool { - var validTemplates = []string{"${status}", "${method}"} + validTemplates := []string{"${status}", "${method}"} if format == "" { return true } diff --git a/middleware/logger/logger.go b/middleware/logger/logger.go index 21fe3eb38f..0431673f5f 100644 --- a/middleware/logger/logger.go +++ b/middleware/logger/logger.go @@ -123,8 +123,8 @@ func New(config ...Config) fiber.Handler { cfg.Output = colorable.NewNonColorable(os.Stderr) } } - var errPadding = 15 - var errPaddingStr = strconv.Itoa(errPadding) + errPadding := 15 + errPaddingStr := strconv.Itoa(errPadding) // Return new handler return func(c *fiber.Ctx) (err error) { // Don't execute middleware if Next returns true diff --git a/middleware/monitor/monitor.go b/middleware/monitor/monitor.go index c687294bf9..71b601f840 100644 --- a/middleware/monitor/monitor.go +++ b/middleware/monitor/monitor.go @@ -24,6 +24,7 @@ type statsPID struct { RAM uint64 `json:"ram"` Conns int `json:"conns"` } + type statsOS struct { CPU float64 `json:"cpu"` RAM uint64 `json:"ram"` diff --git a/middleware/proxy/proxy.go b/middleware/proxy/proxy.go index 09d91d942c..a15e5f96b7 100644 --- a/middleware/proxy/proxy.go +++ b/middleware/proxy/proxy.go @@ -3,11 +3,12 @@ package proxy import ( "crypto/tls" "fmt" + "net/url" + "strings" + "github.com/gofiber/fiber/v2" "github.com/gofiber/fiber/v2/utils" "github.com/valyala/fasthttp" - "net/url" - "strings" ) // New is deprecated diff --git a/middleware/proxy/proxy_test.go b/middleware/proxy/proxy_test.go index c998f302d1..d7665c2dbd 100644 --- a/middleware/proxy/proxy_test.go +++ b/middleware/proxy/proxy_test.go @@ -2,7 +2,6 @@ package proxy import ( "crypto/tls" - "github.com/gofiber/fiber/v2/internal/tlstest" "io/ioutil" "net" "net/http/httptest" @@ -11,10 +10,13 @@ import ( "time" "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/internal/tlstest" "github.com/gofiber/fiber/v2/utils" ) func createProxyTestServer(handler fiber.Handler, t *testing.T) (*fiber.App, string) { + t.Helper() + target := fiber.New(fiber.Config{DisableStartupMessage: true}) target.Get("/", handler) @@ -88,7 +90,7 @@ func Test_Proxy(t *testing.T) { func Test_Proxy_Balancer_WithTlsConfig(t *testing.T) { t.Parallel() - serverTLSConf, clientTLSConf, err := tlstest.GetTLSConfigs() + serverTLSConf, _, err := tlstest.GetTLSConfigs() utils.AssertEqual(t, nil, err) ln, err := net.Listen(fiber.NetworkTCP4, "127.0.0.1:0") @@ -103,7 +105,7 @@ func Test_Proxy_Balancer_WithTlsConfig(t *testing.T) { }) addr := ln.Addr().String() - clientTLSConf = &tls.Config{InsecureSkipVerify: true} + clientTLSConf := &tls.Config{InsecureSkipVerify: true} // disable certificate verification in Balancer app.Use(Balancer(Config{ @@ -145,7 +147,7 @@ func Test_Proxy_Forward(t *testing.T) { func Test_Proxy_Forward_WithTlsConfig(t *testing.T) { t.Parallel() - serverTLSConf, clientTLSConf, err := tlstest.GetTLSConfigs() + serverTLSConf, _, err := tlstest.GetTLSConfigs() utils.AssertEqual(t, nil, err) ln, err := net.Listen(fiber.NetworkTCP4, "127.0.0.1:0") @@ -160,7 +162,7 @@ func Test_Proxy_Forward_WithTlsConfig(t *testing.T) { }) addr := ln.Addr().String() - clientTLSConf = &tls.Config{InsecureSkipVerify: true} + clientTLSConf := &tls.Config{InsecureSkipVerify: true} // disable certificate verification WithTlsConfig(clientTLSConf) diff --git a/middleware/session/data.go b/middleware/session/data.go index 4bbd36241a..917179467b 100644 --- a/middleware/session/data.go +++ b/middleware/session/data.go @@ -25,11 +25,6 @@ func acquireData() *data { return dataPool.Get().(*data) } -func releaseData(d *data) { - d.Reset() - dataPool.Put(d) -} - func (d *data) Reset() { d.Lock() for key := range d.Data { diff --git a/middleware/session/session.go b/middleware/session/session.go index d3e1237b22..99f33a50c0 100644 --- a/middleware/session/session.go +++ b/middleware/session/session.go @@ -112,7 +112,6 @@ func (s *Session) Destroy() error { // Regenerate generates a new session id and delete the old one from Storage func (s *Session) Regenerate() error { - // Delete old id from storage if err := s.config.Storage.Delete(s.id); err != nil { return err @@ -135,7 +134,6 @@ func (s *Session) refresh() { // Save will update the storage and client cookie func (s *Session) Save() error { - // Better safe than sorry if s.data == nil { return nil @@ -176,7 +174,7 @@ func (s *Session) Save() error { return nil } -// Keys will retrive all keys in current session +// Keys will retrieve all keys in current session func (s *Session) Keys() []string { if s.data == nil { return []string{} diff --git a/path.go b/path.go index f488911585..c847db4414 100644 --- a/path.go +++ b/path.go @@ -183,7 +183,7 @@ func (routeParser *routeParser) analyseParameterPart(pattern string) (string, *r } else if parameterEndPosition == -1 { parameterEndPosition = len(pattern) - 1 } else if !isInCharset(pattern[parameterEndPosition+1], parameterDelimiterChars) { - parameterEndPosition = parameterEndPosition + 1 + parameterEndPosition++ } // cut params part processedPart := pattern[0 : parameterEndPosition+1] diff --git a/path_test.go b/path_test.go index f4a0ca6e0d..246cd58f5d 100644 --- a/path_test.go +++ b/path_test.go @@ -232,11 +232,11 @@ func Test_Path_matchParams(t *testing.T) { // optional parameters are not greedy testCase("/:param1:param2?:param3", []testparams{ {url: "/abbbc", params: []string{"a", "b", "bbc"}, match: true}, - //{url: "/ac", params: []string{"a", "", "c"}, match: true}, // TODO: fix it + // {url: "/ac", params: []string{"a", "", "c"}, match: true}, // TODO: fix it {url: "/test", params: []string{"t", "e", "st"}, match: true}, }) testCase("/test:optional?:mandatory", []testparams{ - //{url: "/testo", params: []string{"", "o"}, match: true}, // TODO: fix it + // {url: "/testo", params: []string{"", "o"}, match: true}, // TODO: fix it {url: "/testoaaa", params: []string{"o", "aaa"}, match: true}, {url: "/test", params: nil, match: false}, }) @@ -325,7 +325,7 @@ func Test_Path_matchParams(t *testing.T) { {url: "/api/1-", params: nil, match: false}, {url: "/api/1--", params: []string{"1", "", ""}, match: true}, {url: "/api/1-/", params: nil, match: false}, - //{url: "/api/1-/-", params: nil, match: false}, // TODO: fix this part + // {url: "/api/1-/-", params: nil, match: false}, // TODO: fix this part {url: "/api/1-2", params: nil, match: false}, {url: "/api/1-2-", params: []string{"1", "2", ""}, match: true}, {url: "/api/1-2-3", params: []string{"1", "2", "3"}, match: true}, diff --git a/prefork.go b/prefork.go index 4acc35d727..6adfe40f4e 100644 --- a/prefork.go +++ b/prefork.go @@ -19,9 +19,7 @@ const ( envPreforkChildVal = "1" ) -var ( - testPreforkMaster = false -) +var testPreforkMaster = false // IsChild determines if the current process is a child of Prefork func IsChild() bool { @@ -64,9 +62,9 @@ func (app *App) prefork(network, addr string, tlsConfig *tls.Config) (err error) err error } // create variables - var max = runtime.GOMAXPROCS(0) - var childs = make(map[int]*exec.Cmd) - var channel = make(chan child, max) + max := runtime.GOMAXPROCS(0) + childs := make(map[int]*exec.Cmd) + channel := make(chan child, max) // kill child procs when master exits defer func() { diff --git a/prefork_test.go b/prefork_test.go index 0f879b985d..22dcfa6f68 100644 --- a/prefork_test.go +++ b/prefork_test.go @@ -89,9 +89,13 @@ func Test_App_Prefork_Child_Process_Never_Show_Startup_Message(t *testing.T) { } func setupIsChild(t *testing.T) { + t.Helper() + utils.AssertEqual(t, nil, os.Setenv(envPreforkChildKey, envPreforkChildVal)) } func teardownIsChild(t *testing.T) { + t.Helper() + utils.AssertEqual(t, nil, os.Setenv(envPreforkChildKey, "")) } diff --git a/router.go b/router.go index 98f34cb81a..dcbda99734 100644 --- a/router.go +++ b/router.go @@ -236,14 +236,14 @@ func (app *App) register(method, pathRaw string, handlers ...Handler) Router { pathPretty = utils.TrimRight(pathPretty, '/') } // Is layer a middleware? - var isUse = method == methodUse + isUse := method == methodUse // Is path a direct wildcard? - var isStar = pathPretty == "/*" + isStar := pathPretty == "/*" // Is path a root slash? - var isRoot = pathPretty == "/" + isRoot := pathPretty == "/" // Parse path parameters - var parsedRaw = parseRoute(pathRaw) - var parsedPretty = parseRoute(pathPretty) + parsedRaw := parseRoute(pathRaw) + parsedPretty := parseRoute(pathPretty) // Create route metadata without pointer route := Route{ @@ -302,9 +302,9 @@ func (app *App) registerStatic(prefix, root string, config ...Static) Router { root = root[:len(root)-1] } // Is prefix a direct wildcard? - var isStar = prefix == "/*" + isStar := prefix == "/*" // Is prefix a root slash? - var isRoot = prefix == "/" + isRoot := prefix == "/" // Is prefix a partial wildcard? if strings.Contains(prefix, "*") { // /john* -> /john diff --git a/router_test.go b/router_test.go index c33761d2f3..ac92f16b70 100644 --- a/router_test.go +++ b/router_test.go @@ -422,7 +422,6 @@ func Test_Route_Static_HasPrefix(t *testing.T) { utils.AssertEqual(t, nil, err, "app.Test(req)") utils.AssertEqual(t, true, strings.Contains(app.getString(body), "color")) - app = New() app.Static("/static/", dir) @@ -784,13 +783,13 @@ func Benchmark_Router_Github_API(b *testing.B) { utils.AssertEqual(b, nil, err) utils.AssertEqual(b, true, match) } - } type testRoute struct { Method string `json:"method"` Path string `json:"path"` } + type routeJSON struct { TestRoutes []testRoute `json:"testRoutes"` GithubAPI []testRoute `json:"githubAPI"` diff --git a/utils/assertions.go b/utils/assertions.go index 348e3985ed..ec9a119c0f 100644 --- a/utils/assertions.go +++ b/utils/assertions.go @@ -16,13 +16,17 @@ import ( ) // AssertEqual checks if values are equal -func AssertEqual(t testing.TB, expected, actual interface{}, description ...string) { +func AssertEqual(tb testing.TB, expected, actual interface{}, description ...string) { + if tb != nil { + tb.Helper() + } + if reflect.DeepEqual(expected, actual) { return } - var aType = "" - var bType = "" + aType := "" + bType := "" if expected != nil { aType = reflect.TypeOf(expected).String() @@ -32,8 +36,8 @@ func AssertEqual(t testing.TB, expected, actual interface{}, description ...stri } testName := "AssertEqual" - if t != nil { - testName = t.Name() + if tb != nil { + testName = tb.Name() } _, file, line, _ := runtime.Caller(1) @@ -55,8 +59,8 @@ func AssertEqual(t testing.TB, expected, actual interface{}, description ...stri result = buf.String() } - if t != nil { - t.Fatal(result) + if tb != nil { + tb.Fatal(result) } else { log.Fatal(result) } diff --git a/utils/bytes_test.go b/utils/bytes_test.go index 55bad6b3fa..3c180daef5 100644 --- a/utils/bytes_test.go +++ b/utils/bytes_test.go @@ -24,7 +24,7 @@ func Test_ToLowerBytes(t *testing.T) { } func Benchmark_ToLowerBytes(b *testing.B) { - var path = []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts") + path := []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts") var res []byte b.Run("fiber", func(b *testing.B) { @@ -56,7 +56,7 @@ func Test_ToUpperBytes(t *testing.T) { } func Benchmark_ToUpperBytes(b *testing.B) { - var path = []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts") + path := []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts") var res []byte b.Run("fiber", func(b *testing.B) { @@ -107,6 +107,7 @@ func Test_TrimLeftBytes(t *testing.T) { res = TrimLeftBytes([]byte("test/"), '/') AssertEqual(t, []byte("test/"), res) } + func Benchmark_TrimLeftBytes(b *testing.B) { var res []byte @@ -123,6 +124,7 @@ func Benchmark_TrimLeftBytes(b *testing.B) { AssertEqual(b, []byte("foobar"), res) }) } + func Test_TrimBytes(t *testing.T) { t.Parallel() res := TrimBytes([]byte(" test "), ' ') @@ -134,6 +136,7 @@ func Test_TrimBytes(t *testing.T) { res = TrimBytes([]byte(".test"), '.') AssertEqual(t, []byte("test"), res) } + func Benchmark_TrimBytes(b *testing.B) { var res []byte @@ -152,8 +155,8 @@ func Benchmark_TrimBytes(b *testing.B) { } func Benchmark_EqualFoldBytes(b *testing.B) { - var left = []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts") - var right = []byte("/RePos/goFiber/Fiber/issues/187643/COMMENTS") + left := []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts") + right := []byte("/RePos/goFiber/Fiber/issues/187643/COMMENTS") var res bool b.Run("fiber", func(b *testing.B) { diff --git a/utils/common.go b/utils/common.go index 1d238f0e71..904c292473 100644 --- a/utils/common.go +++ b/utils/common.go @@ -18,16 +18,20 @@ import ( googleuuid "github.com/gofiber/fiber/v2/internal/uuid" ) -const toLowerTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" -const toUpperTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" +const ( + toLowerTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@abcdefghijklmnopqrstuvwxyz[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" + toUpperTable = "\x00\x01\x02\x03\x04\x05\x06\a\b\t\n\v\f\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`ABCDEFGHIJKLMNOPQRSTUVWXYZ{|}~\u007f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" +) // Copyright © 2014, Roger Peppe // github.com/rogpeppe/fastuuid // All rights reserved. -var uuidSeed [24]byte -var uuidCounter uint64 -var uuidSetup sync.Once +var ( + uuidSeed [24]byte + uuidCounter uint64 + uuidSetup sync.Once +) // UUID generates an universally unique identifier (UUID) func UUID() string { diff --git a/utils/common_test.go b/utils/common_test.go index fa33546b8a..4c1ad2ac95 100644 --- a/utils/common_test.go +++ b/utils/common_test.go @@ -16,7 +16,7 @@ func Test_FunctionName(t *testing.T) { AssertEqual(t, "github.com/gofiber/fiber/v2/utils.Test_FunctionName.func1", FunctionName(func() {})) - var dummyint = 20 + dummyint := 20 AssertEqual(t, "int", FunctionName(dummyint)) } @@ -51,6 +51,7 @@ func Test_UUIDv4(t *testing.T) { AssertEqual(t, 36, len(res)) AssertEqual(t, true, res != "00000000-0000-0000-0000-000000000000") } + func Test_UUIDv4_Concurrency(t *testing.T) { t.Parallel() iterations := 1000 diff --git a/utils/convert.go b/utils/convert.go index 08d4abc9a7..ae99723438 100644 --- a/utils/convert.go +++ b/utils/convert.go @@ -58,22 +58,22 @@ func ByteSize(bytes uint64) string { switch { case bytes >= uExabyte: unit = "EB" - value = value / uExabyte + value /= uExabyte case bytes >= uPetabyte: unit = "PB" - value = value / uPetabyte + value /= uPetabyte case bytes >= uTerabyte: unit = "TB" - value = value / uTerabyte + value /= uTerabyte case bytes >= uGigabyte: unit = "GB" - value = value / uGigabyte + value /= uGigabyte case bytes >= uMegabyte: unit = "MB" - value = value / uMegabyte + value /= uMegabyte case bytes >= uKilobyte: unit = "KB" - value = value / uKilobyte + value /= uKilobyte case bytes >= uByte: unit = "B" default: diff --git a/utils/convert_test.go b/utils/convert_test.go index 17723ebe44..d788dead42 100644 --- a/utils/convert_test.go +++ b/utils/convert_test.go @@ -15,7 +15,7 @@ func Test_UnsafeString(t *testing.T) { // go test -v -run=^$ -bench=UnsafeString -benchmem -count=2 func Benchmark_UnsafeString(b *testing.B) { - var hello = []byte("Hello, World!") + hello := []byte("Hello, World!") var res string b.Run("unsafe", func(b *testing.B) { for n := 0; n < b.N; n++ { @@ -40,7 +40,7 @@ func Test_UnsafeBytes(t *testing.T) { // go test -v -run=^$ -bench=UnsafeBytes -benchmem -count=4 func Benchmark_UnsafeBytes(b *testing.B) { - var hello = "Hello, World!" + hello := "Hello, World!" var res []byte b.Run("unsafe", func(b *testing.B) { for n := 0; n < b.N; n++ { diff --git a/utils/strings.go b/utils/strings.go index fe84c33f7c..dcdd8da736 100644 --- a/utils/strings.go +++ b/utils/strings.go @@ -6,7 +6,7 @@ package utils // ToLower is the equivalent of strings.ToLower func ToLower(b string) string { - var res = make([]byte, len(b)) + res := make([]byte, len(b)) copy(res, b) for i := 0; i < len(res); i++ { res[i] = toLowerTable[res[i]] @@ -17,7 +17,7 @@ func ToLower(b string) string { // ToUpper is the equivalent of strings.ToUpper func ToUpper(b string) string { - var res = make([]byte, len(b)) + res := make([]byte, len(b)) copy(res, b) for i := 0; i < len(res); i++ { res[i] = toUpperTable[res[i]] diff --git a/utils/strings_test.go b/utils/strings_test.go index ca8e95268a..2ebb32838b 100644 --- a/utils/strings_test.go +++ b/utils/strings_test.go @@ -16,7 +16,7 @@ func Test_ToUpper(t *testing.T) { } func Benchmark_ToUpper(b *testing.B) { - var path = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts" + path := "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts" var res string b.Run("fiber", func(b *testing.B) { @@ -48,7 +48,7 @@ func Test_ToLower(t *testing.T) { } func Benchmark_ToLower(b *testing.B) { - var path = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts" + path := "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts" var res string b.Run("fiber", func(b *testing.B) { for n := 0; n < b.N; n++ { @@ -72,6 +72,7 @@ func Test_TrimRight(t *testing.T) { res = TrimRight("/test", '/') AssertEqual(t, "/test", res) } + func Benchmark_TrimRight(b *testing.B) { var res string @@ -97,6 +98,7 @@ func Test_TrimLeft(t *testing.T) { res = TrimLeft("test/", '/') AssertEqual(t, "test/", res) } + func Benchmark_TrimLeft(b *testing.B) { var res string @@ -113,6 +115,7 @@ func Benchmark_TrimLeft(b *testing.B) { AssertEqual(b, "foobar", res) }) } + func Test_Trim(t *testing.T) { t.Parallel() res := Trim(" test ", ' ') @@ -150,8 +153,8 @@ func Benchmark_Trim(b *testing.B) { // go test -v -run=^$ -bench=Benchmark_EqualFold -benchmem -count=4 func Benchmark_EqualFold(b *testing.B) { - var left = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts" - var right = "/RePos/goFiber/Fiber/issues/187643/COMMENTS" + left := "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts" + right := "/RePos/goFiber/Fiber/issues/187643/COMMENTS" var res bool b.Run("fiber", func(b *testing.B) {