♻️ Tidy up the codebase (#1613)

* run gofmt

* add t.Helper()

* Simplify assigns

* Simplify make operation

* Remove unused field in struct

* Fix typo

* Run gofumpt ./

* Consistent spacing

* len(...) can never be negative

* Use ReplaceAll

* Simplify operation

* Remove deadcode

* Fix typo

* Tidy up `} else { if ...`

* Fix AssertEqual

* Remove t.Helper() to fix go1.14.15
pull/1616/head
Gusted 2021-11-05 08:00:03 +01:00 committed by GitHub
parent a6aea1cdc5
commit 7b7dcf29f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
47 changed files with 156 additions and 154 deletions

2
app.go
View File

@ -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.

View File

@ -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()
}

View File

@ -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() }

24
ctx.go
View File

@ -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)
}

View File

@ -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

View File

@ -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) {

View File

@ -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"

View File

@ -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)
})

View File

@ -2,6 +2,7 @@ package basicauth
import (
"crypto/subtle"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/utils"
)

View File

@ -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) {

View File

@ -79,7 +79,6 @@ func (m *manager) get(key string) (it *item) {
it = m.acquire()
}
return
}
// get raw data from storage or memory

View File

@ -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)

View File

@ -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

View File

@ -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()

View File

@ -2,6 +2,7 @@ package csrf
import (
"errors"
"github.com/gofiber/fiber/v2"
)

View File

@ -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 {

View File

@ -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

View File

@ -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())

View File

@ -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))

View File

@ -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 == "/" {

View File

@ -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) {

View File

@ -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",
},
}

View File

@ -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

View File

@ -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.

View File

@ -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

View File

@ -72,7 +72,6 @@ func (m *manager) get(key string) (it *item) {
it = m.acquire()
}
return
}
// get raw data from storage or memory

View File

@ -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
}

View File

@ -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

View File

@ -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"`

View File

@ -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

View File

@ -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)

View File

@ -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 {

View File

@ -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{}

View File

@ -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]

View File

@ -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},

View File

@ -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() {

View File

@ -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, ""))
}

View File

@ -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

View File

@ -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"`

View File

@ -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 = "<nil>"
var bType = "<nil>"
aType := "<nil>"
bType := "<nil>"
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)
}

View File

@ -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) {

View File

@ -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 {

View File

@ -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

View File

@ -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:

View File

@ -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++ {

View File

@ -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]]

View File

@ -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) {