mirror of https://github.com/gofiber/fiber.git
♻️ 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.15pull/1616/head
parent
a6aea1cdc5
commit
7b7dcf29f7
2
app.go
2
app.go
|
@ -897,7 +897,7 @@ func (app *App) init() *App {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ErrorHandler is the application's method in charge of finding the
|
// 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
|
// sub fibers by their prefixes and if it finds a match, it uses that
|
||||||
// error handler. Otherwise it uses the configured error handler for
|
// error handler. Otherwise it uses the configured error handler for
|
||||||
// the app, which if not set is the DefaultErrorHandler.
|
// the app, which if not set is the DefaultErrorHandler.
|
||||||
|
|
17
app_test.go
17
app_test.go
|
@ -34,6 +34,8 @@ var testEmptyHandler = func(c *Ctx) error {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testStatus200(t *testing.T, app *App, url string, method string) {
|
func testStatus200(t *testing.T, app *App, url string, method string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
req := httptest.NewRequest(method, url, nil)
|
req := httptest.NewRequest(method, url, nil)
|
||||||
|
|
||||||
resp, err := app.Test(req)
|
resp, err := app.Test(req)
|
||||||
|
@ -447,7 +449,6 @@ func Test_App_Chaining(t *testing.T) {
|
||||||
resp, err = app.Test(req)
|
resp, err = app.Test(req)
|
||||||
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
||||||
utils.AssertEqual(t, 203, resp.StatusCode, "Status code")
|
utils.AssertEqual(t, 203, resp.StatusCode, "Status code")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_App_Order(t *testing.T) {
|
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, nil, err)
|
||||||
utils.AssertEqual(t, "123", string(body))
|
utils.AssertEqual(t, "123", string(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_App_Methods(t *testing.T) {
|
func Test_App_Methods(t *testing.T) {
|
||||||
var dummyHandler = testEmptyHandler
|
dummyHandler := testEmptyHandler
|
||||||
|
|
||||||
app := New()
|
app := New()
|
||||||
|
|
||||||
|
@ -515,7 +517,6 @@ func Test_App_Methods(t *testing.T) {
|
||||||
|
|
||||||
app.Use("/:john?/:doe?", dummyHandler)
|
app.Use("/:john?/:doe?", dummyHandler)
|
||||||
testStatus200(t, app, "/john/doe", MethodGet)
|
testStatus200(t, app, "/john/doe", MethodGet)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_App_New(t *testing.T) {
|
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, 200, resp.StatusCode, "Status code")
|
||||||
utils.AssertEqual(t, false, resp.Header.Get(HeaderContentLength) == "")
|
utils.AssertEqual(t, false, resp.Header.Get(HeaderContentLength) == "")
|
||||||
utils.AssertEqual(t, MIMETextHTMLCharsetUTF8, resp.Header.Get(HeaderContentType))
|
utils.AssertEqual(t, MIMETextHTMLCharsetUTF8, resp.Header.Get(HeaderContentType))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_App_Static_Wildcard(t *testing.T) {
|
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)
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, true, strings.Contains(string(body), "Test file"))
|
utils.AssertEqual(t, true, strings.Contains(string(body), "Test file"))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_App_Static_Prefix_Wildcard(t *testing.T) {
|
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) {
|
func Test_App_Group(t *testing.T) {
|
||||||
var dummyHandler = testEmptyHandler
|
dummyHandler := testEmptyHandler
|
||||||
|
|
||||||
app := New()
|
app := New()
|
||||||
|
|
||||||
|
@ -937,18 +936,18 @@ func Test_App_Group(t *testing.T) {
|
||||||
resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", nil))
|
resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", nil))
|
||||||
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
||||||
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
|
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)
|
api.Get("/users", dummyHandler)
|
||||||
resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", nil))
|
resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", nil))
|
||||||
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
||||||
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
|
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) {
|
func Test_App_Deep_Group(t *testing.T) {
|
||||||
runThroughCount := 0
|
runThroughCount := 0
|
||||||
var dummyHandler = func(c *Ctx) error {
|
dummyHandler := func(c *Ctx) error {
|
||||||
runThroughCount++
|
runThroughCount++
|
||||||
return c.Next()
|
return c.Next()
|
||||||
}
|
}
|
||||||
|
|
|
@ -307,7 +307,6 @@ func Test_Client_Agent_Set_Or_Add_Headers(t *testing.T) {
|
||||||
AddBytesKV([]byte("k1"), []byte("v33")).
|
AddBytesKV([]byte("k1"), []byte("v33")).
|
||||||
SetBytesKV([]byte("k2"), []byte("v2")).
|
SetBytesKV([]byte("k2"), []byte("v2")).
|
||||||
Add("k2", "v22")
|
Add("k2", "v22")
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
testAgent(t, handler, wrapAgent, "K1v1K1v11K1v22K1v33K2v2K2v22")
|
testAgent(t, handler, wrapAgent, "K1v1K1v11K1v22K1v33K2v2K2v22")
|
||||||
|
@ -700,7 +699,7 @@ func Test_Client_Agent_MultipartForm_SendFiles(t *testing.T) {
|
||||||
fh1, err := c.FormFile("field1")
|
fh1, err := c.FormFile("field1")
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, fh1.Filename, "name")
|
utils.AssertEqual(t, fh1.Filename, "name")
|
||||||
buf := make([]byte, fh1.Size, fh1.Size)
|
buf := make([]byte, fh1.Size)
|
||||||
f, err := fh1.Open()
|
f, err := fh1.Open()
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
defer func() { _ = f.Close() }()
|
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) {
|
func checkFormFile(t *testing.T, fh *multipart.FileHeader, filename string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
basename := filepath.Base(filename)
|
basename := filepath.Base(filename)
|
||||||
utils.AssertEqual(t, fh.Filename, basename)
|
utils.AssertEqual(t, fh.Filename, basename)
|
||||||
|
|
||||||
b1, err := ioutil.ReadFile(filename)
|
b1, err := ioutil.ReadFile(filename)
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
|
|
||||||
b2 := make([]byte, fh.Size, fh.Size)
|
b2 := make([]byte, fh.Size)
|
||||||
f, err := fh.Open()
|
f, err := fh.Open()
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
defer func() { _ = f.Close() }()
|
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)) }()
|
go func() { utils.AssertEqual(t, nil, app.Listener(ln)) }()
|
||||||
|
|
||||||
t.Run("success", func(t *testing.T) {
|
t.Run("success", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
|
|
||||||
a := Get("http://example.com")
|
a := Get("http://example.com")
|
||||||
|
|
||||||
a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() }
|
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.Run("pre error", func(t *testing.T) {
|
||||||
|
t.Parallel()
|
||||||
a := Get("http://example.com")
|
a := Get("http://example.com")
|
||||||
|
|
||||||
a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() }
|
a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() }
|
||||||
|
|
24
ctx.go
24
ctx.go
|
@ -301,7 +301,7 @@ func SetParserDecoder(parserConfig ParserConfig) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func decoderBuilder(parserConfig ParserConfig) interface{} {
|
func decoderBuilder(parserConfig ParserConfig) interface{} {
|
||||||
var decoder = schema.NewDecoder()
|
decoder := schema.NewDecoder()
|
||||||
decoder.IgnoreUnknownKeys(parserConfig.IgnoreUnknownKeys)
|
decoder.IgnoreUnknownKeys(parserConfig.IgnoreUnknownKeys)
|
||||||
if parserConfig.SetAliasTag != "" {
|
if parserConfig.SetAliasTag != "" {
|
||||||
decoder.SetAliasTag(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
|
// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
|
||||||
func (c *Ctx) Fresh() bool {
|
func (c *Ctx) Fresh() bool {
|
||||||
// fields
|
// fields
|
||||||
var modifiedSince = c.Get(HeaderIfModifiedSince)
|
modifiedSince := c.Get(HeaderIfModifiedSince)
|
||||||
var noneMatch = c.Get(HeaderIfNoneMatch)
|
noneMatch := c.Get(HeaderIfNoneMatch)
|
||||||
|
|
||||||
// unconditional request
|
// unconditional request
|
||||||
if modifiedSince == "" && noneMatch == "" {
|
if modifiedSince == "" && noneMatch == "" {
|
||||||
|
@ -536,7 +536,7 @@ func (c *Ctx) Fresh() bool {
|
||||||
|
|
||||||
// if-none-match
|
// if-none-match
|
||||||
if noneMatch != "" && noneMatch != "*" {
|
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 == "" {
|
if etag == "" {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
@ -545,7 +545,7 @@ func (c *Ctx) Fresh() bool {
|
||||||
}
|
}
|
||||||
|
|
||||||
if modifiedSince != "" {
|
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 != "" {
|
if lastModified != "" {
|
||||||
lastModifiedTime, err := http.ParseTime(lastModified)
|
lastModifiedTime, err := http.ParseTime(lastModified)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
@ -576,7 +576,6 @@ func (c *Ctx) Get(key string, defaultValue ...string) string {
|
||||||
// Make copies or use the Immutable setting instead.
|
// Make copies or use the Immutable setting instead.
|
||||||
func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string {
|
func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string {
|
||||||
return defaultString(c.app.getString(c.fasthttp.Response.Header.Peek(key)), defaultValue)
|
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.
|
// 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.
|
// By default, the callback name is simply callback.
|
||||||
func (c *Ctx) JSONP(data interface{}, callback ...string) error {
|
func (c *Ctx) JSONP(data interface{}, callback ...string) error {
|
||||||
raw, err := json.Marshal(data)
|
raw, err := json.Marshal(data)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
@ -856,7 +854,7 @@ func (c *Ctx) Query(key string, defaultValue ...string) string {
|
||||||
// QueryParser binds the query string to a struct.
|
// QueryParser binds the query string to a struct.
|
||||||
func (c *Ctx) QueryParser(out interface{}) error {
|
func (c *Ctx) QueryParser(out interface{}) error {
|
||||||
// Get decoder from pool
|
// Get decoder from pool
|
||||||
var decoder = decoderPool.Get().(*schema.Decoder)
|
decoder := decoderPool.Get().(*schema.Decoder)
|
||||||
defer decoderPool.Put(decoder)
|
defer decoderPool.Put(decoder)
|
||||||
|
|
||||||
// Set correct alias tag
|
// Set correct alias tag
|
||||||
|
@ -1063,9 +1061,11 @@ func (c *Ctx) Send(body []byte) error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
var sendFileOnce sync.Once
|
var (
|
||||||
var sendFileFS *fasthttp.FS
|
sendFileOnce sync.Once
|
||||||
var sendFileHandler fasthttp.RequestHandler
|
sendFileFS *fasthttp.FS
|
||||||
|
sendFileHandler fasthttp.RequestHandler
|
||||||
|
)
|
||||||
|
|
||||||
// SendFile transfers the file from the given path.
|
// SendFile transfers the file from the given path.
|
||||||
// The file is not compressed by default, enable this by passing a 'true' argument
|
// 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
|
// Keep original path for mutable params
|
||||||
c.pathOriginal = utils.CopyString(c.pathOriginal)
|
c.pathOriginal = utils.CopyString(c.pathOriginal)
|
||||||
// Disable compression
|
// Disable compression
|
||||||
if len(compress) <= 0 || !compress[0] {
|
if len(compress) == 0 || !compress[0] {
|
||||||
// https://github.com/valyala/fasthttp/blob/master/fs.go#L46
|
// https://github.com/valyala/fasthttp/blob/master/fs.go#L46
|
||||||
c.fasthttp.Request.Header.Del(HeaderAcceptEncoding)
|
c.fasthttp.Request.Header.Del(HeaderAcceptEncoding)
|
||||||
}
|
}
|
||||||
|
|
30
ctx_test.go
30
ctx_test.go
|
@ -22,7 +22,6 @@ import (
|
||||||
"reflect"
|
"reflect"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
|
||||||
"testing"
|
"testing"
|
||||||
"text/template"
|
"text/template"
|
||||||
"time"
|
"time"
|
||||||
|
@ -403,7 +402,7 @@ func Test_Ctx_BodyParser(t *testing.T) {
|
||||||
func Test_Ctx_BodyParser_WithSetParserDecoder(t *testing.T) {
|
func Test_Ctx_BodyParser_WithSetParserDecoder(t *testing.T) {
|
||||||
type CustomTime time.Time
|
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 {
|
if v, err := time.Parse("2006-01-02", value); err == nil {
|
||||||
return reflect.ValueOf(v)
|
return reflect.ValueOf(v)
|
||||||
}
|
}
|
||||||
|
@ -567,7 +566,6 @@ func Test_Ctx_UserContext(t *testing.T) {
|
||||||
t.Run("Nil_Context", func(t *testing.T) {
|
t.Run("Nil_Context", func(t *testing.T) {
|
||||||
ctx := c.UserContext()
|
ctx := c.UserContext()
|
||||||
utils.AssertEqual(t, ctx, context.Background())
|
utils.AssertEqual(t, ctx, context.Background())
|
||||||
|
|
||||||
})
|
})
|
||||||
t.Run("ValueContext", func(t *testing.T) {
|
t.Run("ValueContext", func(t *testing.T) {
|
||||||
testKey := "Test Key"
|
testKey := "Test Key"
|
||||||
|
@ -634,12 +632,12 @@ func Test_Ctx_Cookie(t *testing.T) {
|
||||||
expire := time.Now().Add(24 * time.Hour)
|
expire := time.Now().Add(24 * time.Hour)
|
||||||
var dst []byte
|
var dst []byte
|
||||||
dst = expire.In(time.UTC).AppendFormat(dst, time.RFC1123)
|
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{
|
cookie := &Cookie{
|
||||||
Name: "username",
|
Name: "username",
|
||||||
Value: "john",
|
Value: "john",
|
||||||
Expires: expire,
|
Expires: expire,
|
||||||
//SameSite: CookieSameSiteStrictMode, // default is "lax"
|
// SameSite: CookieSameSiteStrictMode, // default is "lax"
|
||||||
}
|
}
|
||||||
c.Cookie(cookie)
|
c.Cookie(cookie)
|
||||||
expect := "username=john; expires=" + httpdate + "; path=/; SameSite=Lax"
|
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++ {
|
for n := 0; n < b.N; n++ {
|
||||||
h(c)
|
h(c)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -run Test_Ctx_OriginalURL
|
// go test -run Test_Ctx_OriginalURL
|
||||||
|
@ -1452,19 +1449,19 @@ func Test_Ctx_Range(t *testing.T) {
|
||||||
err error
|
err error
|
||||||
)
|
)
|
||||||
|
|
||||||
result, err = c.Range(1000)
|
_, err = c.Range(1000)
|
||||||
utils.AssertEqual(t, true, err != nil)
|
utils.AssertEqual(t, true, err != nil)
|
||||||
|
|
||||||
c.Request().Header.Set(HeaderRange, "bytes=500")
|
c.Request().Header.Set(HeaderRange, "bytes=500")
|
||||||
result, err = c.Range(1000)
|
_, err = c.Range(1000)
|
||||||
utils.AssertEqual(t, true, err != nil)
|
utils.AssertEqual(t, true, err != nil)
|
||||||
|
|
||||||
c.Request().Header.Set(HeaderRange, "bytes=500=")
|
c.Request().Header.Set(HeaderRange, "bytes=500=")
|
||||||
result, err = c.Range(1000)
|
_, err = c.Range(1000)
|
||||||
utils.AssertEqual(t, true, err != nil)
|
utils.AssertEqual(t, true, err != nil)
|
||||||
|
|
||||||
c.Request().Header.Set(HeaderRange, "bytes=500-300")
|
c.Request().Header.Set(HeaderRange, "bytes=500-300")
|
||||||
result, err = c.Range(1000)
|
_, err = c.Range(1000)
|
||||||
utils.AssertEqual(t, true, err != nil)
|
utils.AssertEqual(t, true, err != nil)
|
||||||
|
|
||||||
testRange := func(header string, start, end int) {
|
testRange := func(header string, start, end int) {
|
||||||
|
@ -1827,7 +1824,7 @@ func Benchmark_Ctx_JSONP(b *testing.B) {
|
||||||
Name: "Grame",
|
Name: "Grame",
|
||||||
Age: 20,
|
Age: 20,
|
||||||
}
|
}
|
||||||
var callback = "emit"
|
callback := "emit"
|
||||||
var err error
|
var err error
|
||||||
b.ReportAllocs()
|
b.ReportAllocs()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
|
@ -1951,7 +1948,6 @@ func Test_Ctx_Render(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
type testTemplateEngine struct {
|
type testTemplateEngine struct {
|
||||||
mu sync.Mutex
|
|
||||||
templates *template.Template
|
templates *template.Template
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -2077,7 +2073,7 @@ func Benchmark_Ctx_Send(b *testing.B) {
|
||||||
app := New()
|
app := New()
|
||||||
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
||||||
defer app.ReleaseCtx(c)
|
defer app.ReleaseCtx(c)
|
||||||
var byt = []byte("Hello, World!")
|
byt := []byte("Hello, World!")
|
||||||
b.ReportAllocs()
|
b.ReportAllocs()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
for n := 0; n < b.N; n++ {
|
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")
|
c.Set("Location", "foo\nSet-Cookie:%20SESSIONID=MaliciousValue\n")
|
||||||
h = string(c.Response().Header.Peek("Location"))
|
h = string(c.Response().Header.Peek("Location"))
|
||||||
utils.AssertEqual(t, false, strings.Contains(h, "\n"), h)
|
utils.AssertEqual(t, false, strings.Contains(h, "\n"), h)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -v -run=^$ -bench=Benchmark_Ctx_Set -benchmem -count=4
|
// go test -v -run=^$ -bench=Benchmark_Ctx_Set -benchmem -count=4
|
||||||
|
@ -2166,7 +2161,7 @@ func Benchmark_Ctx_Set(b *testing.B) {
|
||||||
app := New()
|
app := New()
|
||||||
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
||||||
defer app.ReleaseCtx(c)
|
defer app.ReleaseCtx(c)
|
||||||
var val = "1431-15132-3423"
|
val := "1431-15132-3423"
|
||||||
b.ReportAllocs()
|
b.ReportAllocs()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
|
@ -2272,7 +2267,7 @@ func Benchmark_Ctx_Write(b *testing.B) {
|
||||||
app := New()
|
app := New()
|
||||||
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
||||||
defer app.ReleaseCtx(c)
|
defer app.ReleaseCtx(c)
|
||||||
var byt = []byte("Hello, World!")
|
byt := []byte("Hello, World!")
|
||||||
b.ReportAllocs()
|
b.ReportAllocs()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
for n := 0; n < b.N; n++ {
|
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) {
|
func Test_Ctx_QueryParser_WithSetParserDecoder(t *testing.T) {
|
||||||
type NonRFCTime time.Time
|
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 {
|
if v, err := time.Parse("2006-01-02", value); err == nil {
|
||||||
return reflect.ValueOf(v)
|
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, "/testnoint/xd", nil))
|
||||||
app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", nil))
|
app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", nil))
|
||||||
app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", nil))
|
app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", nil))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -run Test_Ctx_GetRespHeader
|
// go test -run Test_Ctx_GetRespHeader
|
||||||
|
|
2
group.go
2
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...
|
// This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
|
||||||
func (grp *Group) Use(args ...interface{}) Router {
|
func (grp *Group) Use(args ...interface{}) Router {
|
||||||
var prefix = ""
|
prefix := ""
|
||||||
var handlers []Handler
|
var handlers []Handler
|
||||||
for i := 0; i < len(args); i++ {
|
for i := 0; i < len(args); i++ {
|
||||||
switch arg := args[i].(type) {
|
switch arg := args[i].(type) {
|
||||||
|
|
|
@ -122,7 +122,7 @@ func methodExist(ctx *Ctx) (exist bool) {
|
||||||
}
|
}
|
||||||
// Get stack length
|
// Get stack length
|
||||||
lenr := len(tree) - 1
|
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 {
|
for ctx.indexRoute < lenr {
|
||||||
// Increment route index
|
// Increment route index
|
||||||
ctx.indexRoute++
|
ctx.indexRoute++
|
||||||
|
@ -182,7 +182,7 @@ func setETag(c *Ctx, weak bool) {
|
||||||
}
|
}
|
||||||
body := c.fasthttp.Response.Body()
|
body := c.fasthttp.Response.Body()
|
||||||
// Skips ETag if no response body is present
|
// Skips ETag if no response body is present
|
||||||
if len(body) <= 0 {
|
if len(body) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Get ETag header from request
|
// Get ETag header from request
|
||||||
|
@ -344,6 +344,7 @@ type testAddr string
|
||||||
func (a testAddr) Network() string {
|
func (a testAddr) Network() string {
|
||||||
return string(a)
|
return string(a)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a testAddr) String() string {
|
func (a testAddr) String() string {
|
||||||
return string(a)
|
return string(a)
|
||||||
}
|
}
|
||||||
|
@ -689,7 +690,7 @@ const (
|
||||||
NetworkTCP6 = "tcp6"
|
NetworkTCP6 = "tcp6"
|
||||||
)
|
)
|
||||||
|
|
||||||
//Compression types
|
// Compression types
|
||||||
const (
|
const (
|
||||||
StrGzip = "gzip"
|
StrGzip = "gzip"
|
||||||
StrBr = "br"
|
StrBr = "br"
|
||||||
|
|
|
@ -333,7 +333,6 @@ func Benchmark_SlashRecognition(b *testing.B) {
|
||||||
c := int32(slashDelimiter)
|
c := int32(slashDelimiter)
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
result = IndexRune(search, c)
|
result = IndexRune(search, c)
|
||||||
|
|
||||||
}
|
}
|
||||||
utils.AssertEqual(b, true, result)
|
utils.AssertEqual(b, true, result)
|
||||||
})
|
})
|
||||||
|
|
|
@ -2,6 +2,7 @@ package basicauth
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
"github.com/gofiber/fiber/v2/utils"
|
"github.com/gofiber/fiber/v2/utils"
|
||||||
)
|
)
|
||||||
|
|
|
@ -278,7 +278,6 @@ func Test_CustomKey(t *testing.T) {
|
||||||
_, err := app.Test(req)
|
_, err := app.Test(req)
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, true, called)
|
utils.AssertEqual(t, true, called)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_CacheHeader(t *testing.T) {
|
func Test_CacheHeader(t *testing.T) {
|
||||||
|
|
|
@ -79,7 +79,6 @@ func (m *manager) get(key string) (it *item) {
|
||||||
it = m.acquire()
|
it = m.acquire()
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// get raw data from storage or memory
|
// get raw data from storage or memory
|
||||||
|
|
|
@ -90,12 +90,12 @@ func New(config ...Config) fiber.Handler {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert string to slice
|
// Convert string to slice
|
||||||
allowOrigins := strings.Split(strings.Replace(cfg.AllowOrigins, " ", "", -1), ",")
|
allowOrigins := strings.Split(strings.ReplaceAll(cfg.AllowOrigins, " ", ""), ",")
|
||||||
|
|
||||||
// Strip white spaces
|
// Strip white spaces
|
||||||
allowMethods := strings.Replace(cfg.AllowMethods, " ", "", -1)
|
allowMethods := strings.ReplaceAll(cfg.AllowMethods, " ", "")
|
||||||
allowHeaders := strings.Replace(cfg.AllowHeaders, " ", "", -1)
|
allowHeaders := strings.ReplaceAll(cfg.AllowHeaders, " ", "")
|
||||||
exposeHeaders := strings.Replace(cfg.ExposeHeaders, " ", "", -1)
|
exposeHeaders := strings.ReplaceAll(cfg.ExposeHeaders, " ", "")
|
||||||
|
|
||||||
// Convert int to string
|
// Convert int to string
|
||||||
maxAge := strconv.Itoa(cfg.MaxAge)
|
maxAge := strconv.Itoa(cfg.MaxAge)
|
||||||
|
|
|
@ -24,6 +24,8 @@ func Test_CORS_Empty_Config(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDefaultOrEmptyConfig(t *testing.T, app *fiber.App) {
|
func testDefaultOrEmptyConfig(t *testing.T, app *fiber.App) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
h := app.Handler()
|
h := app.Handler()
|
||||||
|
|
||||||
// Test default GET response headers
|
// 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, "true", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlAllowCredentials)))
|
||||||
utils.AssertEqual(t, "X-Request-ID", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlExposeHeaders)))
|
utils.AssertEqual(t, "X-Request-ID", string(ctx.Response.Header.Peek(fiber.HeaderAccessControlExposeHeaders)))
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -run -v Test_CORS_Subdomain
|
// go test -run -v Test_CORS_Subdomain
|
||||||
|
|
|
@ -28,8 +28,6 @@ func Test_CSRF(t *testing.T) {
|
||||||
// Generate CSRF token
|
// Generate CSRF token
|
||||||
ctx.Request.Header.SetMethod(method)
|
ctx.Request.Header.SetMethod(method)
|
||||||
h(ctx)
|
h(ctx)
|
||||||
token := string(ctx.Response.Header.Peek(fiber.HeaderSetCookie))
|
|
||||||
token = strings.Split(strings.Split(token, ";")[0], "=")[1]
|
|
||||||
|
|
||||||
// Without CSRF cookie
|
// Without CSRF cookie
|
||||||
ctx.Request.Reset()
|
ctx.Request.Reset()
|
||||||
|
@ -51,7 +49,7 @@ func Test_CSRF(t *testing.T) {
|
||||||
ctx.Response.Reset()
|
ctx.Response.Reset()
|
||||||
ctx.Request.Header.SetMethod(method)
|
ctx.Request.Header.SetMethod(method)
|
||||||
h(ctx)
|
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]
|
token = strings.Split(strings.Split(token, ";")[0], "=")[1]
|
||||||
|
|
||||||
ctx.Request.Reset()
|
ctx.Request.Reset()
|
||||||
|
|
|
@ -2,6 +2,7 @@ package csrf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"errors"
|
"errors"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
|
@ -12,8 +12,7 @@ import (
|
||||||
// msgp -file="manager.go" -o="manager_msgp.go" -tests=false -unexported
|
// msgp -file="manager.go" -o="manager_msgp.go" -tests=false -unexported
|
||||||
// don't forget to replace the msgp import path to:
|
// don't forget to replace the msgp import path to:
|
||||||
// "github.com/gofiber/fiber/v2/internal/msgp"
|
// "github.com/gofiber/fiber/v2/internal/msgp"
|
||||||
type item struct {
|
type item struct{}
|
||||||
}
|
|
||||||
|
|
||||||
//msgp:ignore manager
|
//msgp:ignore manager
|
||||||
type manager struct {
|
type manager struct {
|
||||||
|
|
|
@ -8,15 +8,17 @@ import (
|
||||||
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
|
"github.com/gofiber/fiber/v2/internal/bytebufferpool"
|
||||||
)
|
)
|
||||||
|
|
||||||
var normalizedHeaderETag = []byte("Etag")
|
var (
|
||||||
var weakPrefix = []byte("W/")
|
normalizedHeaderETag = []byte("Etag")
|
||||||
|
weakPrefix = []byte("W/")
|
||||||
|
)
|
||||||
|
|
||||||
// New creates a new middleware handler
|
// New creates a new middleware handler
|
||||||
func New(config ...Config) fiber.Handler {
|
func New(config ...Config) fiber.Handler {
|
||||||
// Set default config
|
// Set default config
|
||||||
cfg := configDefault(config...)
|
cfg := configDefault(config...)
|
||||||
|
|
||||||
var crc32q = crc32.MakeTable(0xD5828281)
|
crc32q := crc32.MakeTable(0xD5828281)
|
||||||
|
|
||||||
// Return new handler
|
// Return new handler
|
||||||
return func(c *fiber.Ctx) (err error) {
|
return func(c *fiber.Ctx) (err error) {
|
||||||
|
@ -36,7 +38,7 @@ func New(config ...Config) fiber.Handler {
|
||||||
}
|
}
|
||||||
body := c.Response().Body()
|
body := c.Response().Body()
|
||||||
// Skips ETag if no response body is present
|
// Skips ETag if no response body is present
|
||||||
if len(body) <= 0 {
|
if len(body) == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// Skip ETag if header is already present
|
// Skip ETag if header is already present
|
||||||
|
|
|
@ -84,6 +84,8 @@ func Test_ETag_NewEtag(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testETagNewEtag(t *testing.T, headerIfNoneMatch, matched bool) {
|
func testETagNewEtag(t *testing.T, headerIfNoneMatch, matched bool) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
|
||||||
app.Use(New())
|
app.Use(New())
|
||||||
|
@ -132,6 +134,8 @@ func Test_ETag_WeakEtag(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testETagWeakEtag(t *testing.T, headerIfNoneMatch, matched bool) {
|
func testETagWeakEtag(t *testing.T, headerIfNoneMatch, matched bool) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
|
||||||
app.Use(New(Config{Weak: true}))
|
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) {
|
func testETagCustomEtag(t *testing.T, headerIfNoneMatch, matched bool) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
|
||||||
app.Use(New())
|
app.Use(New())
|
||||||
|
|
|
@ -82,10 +82,8 @@ func New(config ...Config) fiber.Handler {
|
||||||
if icon, err = ioutil.ReadAll(f); err != nil {
|
if icon, err = ioutil.ReadAll(f); err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
} else {
|
} else if icon, err = ioutil.ReadFile(cfg.File); err != nil {
|
||||||
if icon, err = ioutil.ReadFile(cfg.File); err != nil {
|
panic(err)
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
iconLen = strconv.Itoa(len(icon))
|
iconLen = strconv.Itoa(len(icon))
|
||||||
|
|
|
@ -78,8 +78,7 @@ func Test_Middleware_Favicon_Found(t *testing.T) {
|
||||||
// mockFS wraps local filesystem for the purposes of
|
// mockFS wraps local filesystem for the purposes of
|
||||||
// Test_Middleware_Favicon_FileSystem located below
|
// Test_Middleware_Favicon_FileSystem located below
|
||||||
// TODO use os.Dir if fiber upgrades to 1.16
|
// 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) {
|
func (m mockFS) Open(name string) (http.File, error) {
|
||||||
if name == "/" {
|
if name == "/" {
|
||||||
|
|
|
@ -95,7 +95,7 @@ func New(config ...Config) fiber.Handler {
|
||||||
|
|
||||||
var once sync.Once
|
var once sync.Once
|
||||||
var prefix string
|
var prefix string
|
||||||
var cacheControlStr = "public, max-age=" + strconv.Itoa(cfg.MaxAge)
|
cacheControlStr := "public, max-age=" + strconv.Itoa(cfg.MaxAge)
|
||||||
|
|
||||||
// Return new handler
|
// Return new handler
|
||||||
return func(c *fiber.Ctx) (err error) {
|
return func(c *fiber.Ctx) (err error) {
|
||||||
|
|
|
@ -33,7 +33,7 @@ func Test_FileSystem(t *testing.T) {
|
||||||
}))
|
}))
|
||||||
|
|
||||||
app.Use("/prefix", New(Config{
|
app.Use("/prefix", New(Config{
|
||||||
Root: http.Dir("../../.github/testdata/fs"),
|
Root: http.Dir("../../.github/testdata/fs"),
|
||||||
PathPrefix: "img",
|
PathPrefix: "img",
|
||||||
}))
|
}))
|
||||||
|
|
||||||
|
@ -108,9 +108,9 @@ func Test_FileSystem(t *testing.T) {
|
||||||
contentType: "text/html",
|
contentType: "text/html",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: "PathPrefix should be applied",
|
name: "PathPrefix should be applied",
|
||||||
url: "/prefix/fiber.png",
|
url: "/prefix/fiber.png",
|
||||||
statusCode: 200,
|
statusCode: 200,
|
||||||
contentType: "image/png",
|
contentType: "image/png",
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
|
@ -54,7 +54,6 @@ func (FixedWindow) New(cfg Config) fiber.Handler {
|
||||||
// Set expiration if entry does not exist
|
// Set expiration if entry does not exist
|
||||||
if e.exp == 0 {
|
if e.exp == 0 {
|
||||||
e.exp = ts + expiration
|
e.exp = ts + expiration
|
||||||
|
|
||||||
} else if ts >= e.exp {
|
} else if ts >= e.exp {
|
||||||
// Check if entry is expired
|
// Check if entry is expired
|
||||||
e.currHits = 0
|
e.currHits = 0
|
||||||
|
|
|
@ -54,7 +54,6 @@ func (SlidingWindow) New(cfg Config) fiber.Handler {
|
||||||
// Set expiration if entry does not exist
|
// Set expiration if entry does not exist
|
||||||
if e.exp == 0 {
|
if e.exp == 0 {
|
||||||
e.exp = ts + expiration
|
e.exp = ts + expiration
|
||||||
|
|
||||||
} else if ts >= e.exp {
|
} else if ts >= e.exp {
|
||||||
// The entry has expired, handle the expiration.
|
// The entry has expired, handle the expiration.
|
||||||
// Set the prevHits to the current hits and reset the hits to 0.
|
// Set the prevHits to the current hits and reset the hits to 0.
|
||||||
|
|
|
@ -62,7 +62,6 @@ func Test_Limiter_Concurrency_Store(t *testing.T) {
|
||||||
|
|
||||||
// go test -run Test_Limiter_Concurrency -race -v
|
// go test -run Test_Limiter_Concurrency -race -v
|
||||||
func Test_Limiter_Concurrency(t *testing.T) {
|
func Test_Limiter_Concurrency(t *testing.T) {
|
||||||
|
|
||||||
// Test concurrency using a default store
|
// Test concurrency using a default store
|
||||||
|
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
@ -104,12 +103,10 @@ func Test_Limiter_Concurrency(t *testing.T) {
|
||||||
resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/", nil))
|
resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/", nil))
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, 200, resp.StatusCode)
|
utils.AssertEqual(t, 200, resp.StatusCode)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -run Test_Limiter_No_Skip_Choices -v
|
// go test -run Test_Limiter_No_Skip_Choices -v
|
||||||
func Test_Limiter_No_Skip_Choices(t *testing.T) {
|
func Test_Limiter_No_Skip_Choices(t *testing.T) {
|
||||||
|
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
|
||||||
app.Use(New(Config{
|
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))
|
resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/success", nil))
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, 429, resp.StatusCode)
|
utils.AssertEqual(t, 429, resp.StatusCode)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -run Test_Limiter_Skip_Failed_Requests -v
|
// go test -run Test_Limiter_Skip_Failed_Requests -v
|
||||||
func Test_Limiter_Skip_Failed_Requests(t *testing.T) {
|
func Test_Limiter_Skip_Failed_Requests(t *testing.T) {
|
||||||
|
|
||||||
app := fiber.New()
|
app := fiber.New()
|
||||||
|
|
||||||
app.Use(New(Config{
|
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))
|
resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/success", nil))
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, 200, resp.StatusCode)
|
utils.AssertEqual(t, 200, resp.StatusCode)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -run Test_Limiter_Skip_Successful_Requests -v
|
// go test -run Test_Limiter_Skip_Successful_Requests -v
|
||||||
func Test_Limiter_Skip_Successful_Requests(t *testing.T) {
|
func Test_Limiter_Skip_Successful_Requests(t *testing.T) {
|
||||||
|
|
||||||
// Test concurrency using a default store
|
// Test concurrency using a default store
|
||||||
|
|
||||||
app := fiber.New()
|
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))
|
resp, err = app.Test(httptest.NewRequest(http.MethodGet, "/fail", nil))
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
utils.AssertEqual(t, 400, resp.StatusCode)
|
utils.AssertEqual(t, 400, resp.StatusCode)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// go test -v -run=^$ -bench=Benchmark_Limiter_Custom_Store -benchmem -count=4
|
// go test -v -run=^$ -bench=Benchmark_Limiter_Custom_Store -benchmem -count=4
|
||||||
|
|
|
@ -72,7 +72,6 @@ func (m *manager) get(key string) (it *item) {
|
||||||
it = m.acquire()
|
it = m.acquire()
|
||||||
}
|
}
|
||||||
return
|
return
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// get raw data from storage or memory
|
// get raw data from storage or memory
|
||||||
|
|
|
@ -59,7 +59,7 @@ var ConfigDefault = Config{
|
||||||
|
|
||||||
// Function to check if the logger format is compatible for coloring
|
// Function to check if the logger format is compatible for coloring
|
||||||
func validCustomFormat(format string) bool {
|
func validCustomFormat(format string) bool {
|
||||||
var validTemplates = []string{"${status}", "${method}"}
|
validTemplates := []string{"${status}", "${method}"}
|
||||||
if format == "" {
|
if format == "" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
|
@ -123,8 +123,8 @@ func New(config ...Config) fiber.Handler {
|
||||||
cfg.Output = colorable.NewNonColorable(os.Stderr)
|
cfg.Output = colorable.NewNonColorable(os.Stderr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var errPadding = 15
|
errPadding := 15
|
||||||
var errPaddingStr = strconv.Itoa(errPadding)
|
errPaddingStr := strconv.Itoa(errPadding)
|
||||||
// Return new handler
|
// Return new handler
|
||||||
return func(c *fiber.Ctx) (err error) {
|
return func(c *fiber.Ctx) (err error) {
|
||||||
// Don't execute middleware if Next returns true
|
// Don't execute middleware if Next returns true
|
||||||
|
|
|
@ -24,6 +24,7 @@ type statsPID struct {
|
||||||
RAM uint64 `json:"ram"`
|
RAM uint64 `json:"ram"`
|
||||||
Conns int `json:"conns"`
|
Conns int `json:"conns"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type statsOS struct {
|
type statsOS struct {
|
||||||
CPU float64 `json:"cpu"`
|
CPU float64 `json:"cpu"`
|
||||||
RAM uint64 `json:"ram"`
|
RAM uint64 `json:"ram"`
|
||||||
|
|
|
@ -3,11 +3,12 @@ package proxy
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/url"
|
||||||
|
"strings"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
"github.com/gofiber/fiber/v2/utils"
|
"github.com/gofiber/fiber/v2/utils"
|
||||||
"github.com/valyala/fasthttp"
|
"github.com/valyala/fasthttp"
|
||||||
"net/url"
|
|
||||||
"strings"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// New is deprecated
|
// New is deprecated
|
||||||
|
|
|
@ -2,7 +2,6 @@ package proxy
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"github.com/gofiber/fiber/v2/internal/tlstest"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net"
|
"net"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
@ -11,10 +10,13 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
|
"github.com/gofiber/fiber/v2/internal/tlstest"
|
||||||
"github.com/gofiber/fiber/v2/utils"
|
"github.com/gofiber/fiber/v2/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
func createProxyTestServer(handler fiber.Handler, t *testing.T) (*fiber.App, string) {
|
func createProxyTestServer(handler fiber.Handler, t *testing.T) (*fiber.App, string) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
target := fiber.New(fiber.Config{DisableStartupMessage: true})
|
target := fiber.New(fiber.Config{DisableStartupMessage: true})
|
||||||
target.Get("/", handler)
|
target.Get("/", handler)
|
||||||
|
|
||||||
|
@ -88,7 +90,7 @@ func Test_Proxy(t *testing.T) {
|
||||||
func Test_Proxy_Balancer_WithTlsConfig(t *testing.T) {
|
func Test_Proxy_Balancer_WithTlsConfig(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
serverTLSConf, clientTLSConf, err := tlstest.GetTLSConfigs()
|
serverTLSConf, _, err := tlstest.GetTLSConfigs()
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
|
|
||||||
ln, err := net.Listen(fiber.NetworkTCP4, "127.0.0.1:0")
|
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()
|
addr := ln.Addr().String()
|
||||||
clientTLSConf = &tls.Config{InsecureSkipVerify: true}
|
clientTLSConf := &tls.Config{InsecureSkipVerify: true}
|
||||||
|
|
||||||
// disable certificate verification in Balancer
|
// disable certificate verification in Balancer
|
||||||
app.Use(Balancer(Config{
|
app.Use(Balancer(Config{
|
||||||
|
@ -145,7 +147,7 @@ func Test_Proxy_Forward(t *testing.T) {
|
||||||
func Test_Proxy_Forward_WithTlsConfig(t *testing.T) {
|
func Test_Proxy_Forward_WithTlsConfig(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
|
|
||||||
serverTLSConf, clientTLSConf, err := tlstest.GetTLSConfigs()
|
serverTLSConf, _, err := tlstest.GetTLSConfigs()
|
||||||
utils.AssertEqual(t, nil, err)
|
utils.AssertEqual(t, nil, err)
|
||||||
|
|
||||||
ln, err := net.Listen(fiber.NetworkTCP4, "127.0.0.1:0")
|
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()
|
addr := ln.Addr().String()
|
||||||
clientTLSConf = &tls.Config{InsecureSkipVerify: true}
|
clientTLSConf := &tls.Config{InsecureSkipVerify: true}
|
||||||
|
|
||||||
// disable certificate verification
|
// disable certificate verification
|
||||||
WithTlsConfig(clientTLSConf)
|
WithTlsConfig(clientTLSConf)
|
||||||
|
|
|
@ -25,11 +25,6 @@ func acquireData() *data {
|
||||||
return dataPool.Get().(*data)
|
return dataPool.Get().(*data)
|
||||||
}
|
}
|
||||||
|
|
||||||
func releaseData(d *data) {
|
|
||||||
d.Reset()
|
|
||||||
dataPool.Put(d)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (d *data) Reset() {
|
func (d *data) Reset() {
|
||||||
d.Lock()
|
d.Lock()
|
||||||
for key := range d.Data {
|
for key := range d.Data {
|
||||||
|
|
|
@ -112,7 +112,6 @@ func (s *Session) Destroy() error {
|
||||||
|
|
||||||
// Regenerate generates a new session id and delete the old one from Storage
|
// Regenerate generates a new session id and delete the old one from Storage
|
||||||
func (s *Session) Regenerate() error {
|
func (s *Session) Regenerate() error {
|
||||||
|
|
||||||
// Delete old id from storage
|
// Delete old id from storage
|
||||||
if err := s.config.Storage.Delete(s.id); err != nil {
|
if err := s.config.Storage.Delete(s.id); err != nil {
|
||||||
return err
|
return err
|
||||||
|
@ -135,7 +134,6 @@ func (s *Session) refresh() {
|
||||||
|
|
||||||
// Save will update the storage and client cookie
|
// Save will update the storage and client cookie
|
||||||
func (s *Session) Save() error {
|
func (s *Session) Save() error {
|
||||||
|
|
||||||
// Better safe than sorry
|
// Better safe than sorry
|
||||||
if s.data == nil {
|
if s.data == nil {
|
||||||
return nil
|
return nil
|
||||||
|
@ -176,7 +174,7 @@ func (s *Session) Save() error {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Keys will retrive all keys in current session
|
// Keys will retrieve all keys in current session
|
||||||
func (s *Session) Keys() []string {
|
func (s *Session) Keys() []string {
|
||||||
if s.data == nil {
|
if s.data == nil {
|
||||||
return []string{}
|
return []string{}
|
||||||
|
|
2
path.go
2
path.go
|
@ -183,7 +183,7 @@ func (routeParser *routeParser) analyseParameterPart(pattern string) (string, *r
|
||||||
} else if parameterEndPosition == -1 {
|
} else if parameterEndPosition == -1 {
|
||||||
parameterEndPosition = len(pattern) - 1
|
parameterEndPosition = len(pattern) - 1
|
||||||
} else if !isInCharset(pattern[parameterEndPosition+1], parameterDelimiterChars) {
|
} else if !isInCharset(pattern[parameterEndPosition+1], parameterDelimiterChars) {
|
||||||
parameterEndPosition = parameterEndPosition + 1
|
parameterEndPosition++
|
||||||
}
|
}
|
||||||
// cut params part
|
// cut params part
|
||||||
processedPart := pattern[0 : parameterEndPosition+1]
|
processedPart := pattern[0 : parameterEndPosition+1]
|
||||||
|
|
|
@ -232,11 +232,11 @@ func Test_Path_matchParams(t *testing.T) {
|
||||||
// optional parameters are not greedy
|
// optional parameters are not greedy
|
||||||
testCase("/:param1:param2?:param3", []testparams{
|
testCase("/:param1:param2?:param3", []testparams{
|
||||||
{url: "/abbbc", params: []string{"a", "b", "bbc"}, match: true},
|
{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},
|
{url: "/test", params: []string{"t", "e", "st"}, match: true},
|
||||||
})
|
})
|
||||||
testCase("/test:optional?:mandatory", []testparams{
|
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: "/testoaaa", params: []string{"o", "aaa"}, match: true},
|
||||||
{url: "/test", params: nil, match: false},
|
{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: nil, match: false},
|
||||||
{url: "/api/1--", params: []string{"1", "", ""}, match: true},
|
{url: "/api/1--", params: []string{"1", "", ""}, match: true},
|
||||||
{url: "/api/1-/", params: nil, match: false},
|
{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: nil, match: false},
|
||||||
{url: "/api/1-2-", params: []string{"1", "2", ""}, match: true},
|
{url: "/api/1-2-", params: []string{"1", "2", ""}, match: true},
|
||||||
{url: "/api/1-2-3", params: []string{"1", "2", "3"}, match: true},
|
{url: "/api/1-2-3", params: []string{"1", "2", "3"}, match: true},
|
||||||
|
|
10
prefork.go
10
prefork.go
|
@ -19,9 +19,7 @@ const (
|
||||||
envPreforkChildVal = "1"
|
envPreforkChildVal = "1"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var testPreforkMaster = false
|
||||||
testPreforkMaster = false
|
|
||||||
)
|
|
||||||
|
|
||||||
// IsChild determines if the current process is a child of Prefork
|
// IsChild determines if the current process is a child of Prefork
|
||||||
func IsChild() bool {
|
func IsChild() bool {
|
||||||
|
@ -64,9 +62,9 @@ func (app *App) prefork(network, addr string, tlsConfig *tls.Config) (err error)
|
||||||
err error
|
err error
|
||||||
}
|
}
|
||||||
// create variables
|
// create variables
|
||||||
var max = runtime.GOMAXPROCS(0)
|
max := runtime.GOMAXPROCS(0)
|
||||||
var childs = make(map[int]*exec.Cmd)
|
childs := make(map[int]*exec.Cmd)
|
||||||
var channel = make(chan child, max)
|
channel := make(chan child, max)
|
||||||
|
|
||||||
// kill child procs when master exits
|
// kill child procs when master exits
|
||||||
defer func() {
|
defer func() {
|
||||||
|
|
|
@ -89,9 +89,13 @@ func Test_App_Prefork_Child_Process_Never_Show_Startup_Message(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func setupIsChild(t *testing.T) {
|
func setupIsChild(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
utils.AssertEqual(t, nil, os.Setenv(envPreforkChildKey, envPreforkChildVal))
|
utils.AssertEqual(t, nil, os.Setenv(envPreforkChildKey, envPreforkChildVal))
|
||||||
}
|
}
|
||||||
|
|
||||||
func teardownIsChild(t *testing.T) {
|
func teardownIsChild(t *testing.T) {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
utils.AssertEqual(t, nil, os.Setenv(envPreforkChildKey, ""))
|
utils.AssertEqual(t, nil, os.Setenv(envPreforkChildKey, ""))
|
||||||
}
|
}
|
||||||
|
|
14
router.go
14
router.go
|
@ -236,14 +236,14 @@ func (app *App) register(method, pathRaw string, handlers ...Handler) Router {
|
||||||
pathPretty = utils.TrimRight(pathPretty, '/')
|
pathPretty = utils.TrimRight(pathPretty, '/')
|
||||||
}
|
}
|
||||||
// Is layer a middleware?
|
// Is layer a middleware?
|
||||||
var isUse = method == methodUse
|
isUse := method == methodUse
|
||||||
// Is path a direct wildcard?
|
// Is path a direct wildcard?
|
||||||
var isStar = pathPretty == "/*"
|
isStar := pathPretty == "/*"
|
||||||
// Is path a root slash?
|
// Is path a root slash?
|
||||||
var isRoot = pathPretty == "/"
|
isRoot := pathPretty == "/"
|
||||||
// Parse path parameters
|
// Parse path parameters
|
||||||
var parsedRaw = parseRoute(pathRaw)
|
parsedRaw := parseRoute(pathRaw)
|
||||||
var parsedPretty = parseRoute(pathPretty)
|
parsedPretty := parseRoute(pathPretty)
|
||||||
|
|
||||||
// Create route metadata without pointer
|
// Create route metadata without pointer
|
||||||
route := Route{
|
route := Route{
|
||||||
|
@ -302,9 +302,9 @@ func (app *App) registerStatic(prefix, root string, config ...Static) Router {
|
||||||
root = root[:len(root)-1]
|
root = root[:len(root)-1]
|
||||||
}
|
}
|
||||||
// Is prefix a direct wildcard?
|
// Is prefix a direct wildcard?
|
||||||
var isStar = prefix == "/*"
|
isStar := prefix == "/*"
|
||||||
// Is prefix a root slash?
|
// Is prefix a root slash?
|
||||||
var isRoot = prefix == "/"
|
isRoot := prefix == "/"
|
||||||
// Is prefix a partial wildcard?
|
// Is prefix a partial wildcard?
|
||||||
if strings.Contains(prefix, "*") {
|
if strings.Contains(prefix, "*") {
|
||||||
// /john* -> /john
|
// /john* -> /john
|
||||||
|
|
|
@ -422,7 +422,6 @@ func Test_Route_Static_HasPrefix(t *testing.T) {
|
||||||
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
||||||
utils.AssertEqual(t, true, strings.Contains(app.getString(body), "color"))
|
utils.AssertEqual(t, true, strings.Contains(app.getString(body), "color"))
|
||||||
|
|
||||||
|
|
||||||
app = New()
|
app = New()
|
||||||
app.Static("/static/", dir)
|
app.Static("/static/", dir)
|
||||||
|
|
||||||
|
@ -784,13 +783,13 @@ func Benchmark_Router_Github_API(b *testing.B) {
|
||||||
utils.AssertEqual(b, nil, err)
|
utils.AssertEqual(b, nil, err)
|
||||||
utils.AssertEqual(b, true, match)
|
utils.AssertEqual(b, true, match)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type testRoute struct {
|
type testRoute struct {
|
||||||
Method string `json:"method"`
|
Method string `json:"method"`
|
||||||
Path string `json:"path"`
|
Path string `json:"path"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type routeJSON struct {
|
type routeJSON struct {
|
||||||
TestRoutes []testRoute `json:"testRoutes"`
|
TestRoutes []testRoute `json:"testRoutes"`
|
||||||
GithubAPI []testRoute `json:"githubAPI"`
|
GithubAPI []testRoute `json:"githubAPI"`
|
||||||
|
|
|
@ -16,13 +16,17 @@ import (
|
||||||
)
|
)
|
||||||
|
|
||||||
// AssertEqual checks if values are equal
|
// 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) {
|
if reflect.DeepEqual(expected, actual) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var aType = "<nil>"
|
aType := "<nil>"
|
||||||
var bType = "<nil>"
|
bType := "<nil>"
|
||||||
|
|
||||||
if expected != nil {
|
if expected != nil {
|
||||||
aType = reflect.TypeOf(expected).String()
|
aType = reflect.TypeOf(expected).String()
|
||||||
|
@ -32,8 +36,8 @@ func AssertEqual(t testing.TB, expected, actual interface{}, description ...stri
|
||||||
}
|
}
|
||||||
|
|
||||||
testName := "AssertEqual"
|
testName := "AssertEqual"
|
||||||
if t != nil {
|
if tb != nil {
|
||||||
testName = t.Name()
|
testName = tb.Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
_, file, line, _ := runtime.Caller(1)
|
_, file, line, _ := runtime.Caller(1)
|
||||||
|
@ -55,8 +59,8 @@ func AssertEqual(t testing.TB, expected, actual interface{}, description ...stri
|
||||||
result = buf.String()
|
result = buf.String()
|
||||||
}
|
}
|
||||||
|
|
||||||
if t != nil {
|
if tb != nil {
|
||||||
t.Fatal(result)
|
tb.Fatal(result)
|
||||||
} else {
|
} else {
|
||||||
log.Fatal(result)
|
log.Fatal(result)
|
||||||
}
|
}
|
||||||
|
|
|
@ -24,7 +24,7 @@ func Test_ToLowerBytes(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_ToLowerBytes(b *testing.B) {
|
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
|
var res []byte
|
||||||
|
|
||||||
b.Run("fiber", func(b *testing.B) {
|
b.Run("fiber", func(b *testing.B) {
|
||||||
|
@ -56,7 +56,7 @@ func Test_ToUpperBytes(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_ToUpperBytes(b *testing.B) {
|
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
|
var res []byte
|
||||||
|
|
||||||
b.Run("fiber", func(b *testing.B) {
|
b.Run("fiber", func(b *testing.B) {
|
||||||
|
@ -107,6 +107,7 @@ func Test_TrimLeftBytes(t *testing.T) {
|
||||||
res = TrimLeftBytes([]byte("test/"), '/')
|
res = TrimLeftBytes([]byte("test/"), '/')
|
||||||
AssertEqual(t, []byte("test/"), res)
|
AssertEqual(t, []byte("test/"), res)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_TrimLeftBytes(b *testing.B) {
|
func Benchmark_TrimLeftBytes(b *testing.B) {
|
||||||
var res []byte
|
var res []byte
|
||||||
|
|
||||||
|
@ -123,6 +124,7 @@ func Benchmark_TrimLeftBytes(b *testing.B) {
|
||||||
AssertEqual(b, []byte("foobar"), res)
|
AssertEqual(b, []byte("foobar"), res)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_TrimBytes(t *testing.T) {
|
func Test_TrimBytes(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
res := TrimBytes([]byte(" test "), ' ')
|
res := TrimBytes([]byte(" test "), ' ')
|
||||||
|
@ -134,6 +136,7 @@ func Test_TrimBytes(t *testing.T) {
|
||||||
res = TrimBytes([]byte(".test"), '.')
|
res = TrimBytes([]byte(".test"), '.')
|
||||||
AssertEqual(t, []byte("test"), res)
|
AssertEqual(t, []byte("test"), res)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_TrimBytes(b *testing.B) {
|
func Benchmark_TrimBytes(b *testing.B) {
|
||||||
var res []byte
|
var res []byte
|
||||||
|
|
||||||
|
@ -152,8 +155,8 @@ func Benchmark_TrimBytes(b *testing.B) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_EqualFoldBytes(b *testing.B) {
|
func Benchmark_EqualFoldBytes(b *testing.B) {
|
||||||
var left = []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts")
|
left := []byte("/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts")
|
||||||
var right = []byte("/RePos/goFiber/Fiber/issues/187643/COMMENTS")
|
right := []byte("/RePos/goFiber/Fiber/issues/187643/COMMENTS")
|
||||||
var res bool
|
var res bool
|
||||||
|
|
||||||
b.Run("fiber", func(b *testing.B) {
|
b.Run("fiber", func(b *testing.B) {
|
||||||
|
|
|
@ -18,16 +18,20 @@ import (
|
||||||
googleuuid "github.com/gofiber/fiber/v2/internal/uuid"
|
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 (
|
||||||
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"
|
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
|
// Copyright © 2014, Roger Peppe
|
||||||
// github.com/rogpeppe/fastuuid
|
// github.com/rogpeppe/fastuuid
|
||||||
// All rights reserved.
|
// All rights reserved.
|
||||||
|
|
||||||
var uuidSeed [24]byte
|
var (
|
||||||
var uuidCounter uint64
|
uuidSeed [24]byte
|
||||||
var uuidSetup sync.Once
|
uuidCounter uint64
|
||||||
|
uuidSetup sync.Once
|
||||||
|
)
|
||||||
|
|
||||||
// UUID generates an universally unique identifier (UUID)
|
// UUID generates an universally unique identifier (UUID)
|
||||||
func UUID() string {
|
func UUID() string {
|
||||||
|
|
|
@ -16,7 +16,7 @@ func Test_FunctionName(t *testing.T) {
|
||||||
|
|
||||||
AssertEqual(t, "github.com/gofiber/fiber/v2/utils.Test_FunctionName.func1", FunctionName(func() {}))
|
AssertEqual(t, "github.com/gofiber/fiber/v2/utils.Test_FunctionName.func1", FunctionName(func() {}))
|
||||||
|
|
||||||
var dummyint = 20
|
dummyint := 20
|
||||||
AssertEqual(t, "int", FunctionName(dummyint))
|
AssertEqual(t, "int", FunctionName(dummyint))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -51,6 +51,7 @@ func Test_UUIDv4(t *testing.T) {
|
||||||
AssertEqual(t, 36, len(res))
|
AssertEqual(t, 36, len(res))
|
||||||
AssertEqual(t, true, res != "00000000-0000-0000-0000-000000000000")
|
AssertEqual(t, true, res != "00000000-0000-0000-0000-000000000000")
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_UUIDv4_Concurrency(t *testing.T) {
|
func Test_UUIDv4_Concurrency(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
iterations := 1000
|
iterations := 1000
|
||||||
|
|
|
@ -58,22 +58,22 @@ func ByteSize(bytes uint64) string {
|
||||||
switch {
|
switch {
|
||||||
case bytes >= uExabyte:
|
case bytes >= uExabyte:
|
||||||
unit = "EB"
|
unit = "EB"
|
||||||
value = value / uExabyte
|
value /= uExabyte
|
||||||
case bytes >= uPetabyte:
|
case bytes >= uPetabyte:
|
||||||
unit = "PB"
|
unit = "PB"
|
||||||
value = value / uPetabyte
|
value /= uPetabyte
|
||||||
case bytes >= uTerabyte:
|
case bytes >= uTerabyte:
|
||||||
unit = "TB"
|
unit = "TB"
|
||||||
value = value / uTerabyte
|
value /= uTerabyte
|
||||||
case bytes >= uGigabyte:
|
case bytes >= uGigabyte:
|
||||||
unit = "GB"
|
unit = "GB"
|
||||||
value = value / uGigabyte
|
value /= uGigabyte
|
||||||
case bytes >= uMegabyte:
|
case bytes >= uMegabyte:
|
||||||
unit = "MB"
|
unit = "MB"
|
||||||
value = value / uMegabyte
|
value /= uMegabyte
|
||||||
case bytes >= uKilobyte:
|
case bytes >= uKilobyte:
|
||||||
unit = "KB"
|
unit = "KB"
|
||||||
value = value / uKilobyte
|
value /= uKilobyte
|
||||||
case bytes >= uByte:
|
case bytes >= uByte:
|
||||||
unit = "B"
|
unit = "B"
|
||||||
default:
|
default:
|
||||||
|
|
|
@ -15,7 +15,7 @@ func Test_UnsafeString(t *testing.T) {
|
||||||
// go test -v -run=^$ -bench=UnsafeString -benchmem -count=2
|
// go test -v -run=^$ -bench=UnsafeString -benchmem -count=2
|
||||||
|
|
||||||
func Benchmark_UnsafeString(b *testing.B) {
|
func Benchmark_UnsafeString(b *testing.B) {
|
||||||
var hello = []byte("Hello, World!")
|
hello := []byte("Hello, World!")
|
||||||
var res string
|
var res string
|
||||||
b.Run("unsafe", func(b *testing.B) {
|
b.Run("unsafe", func(b *testing.B) {
|
||||||
for n := 0; n < b.N; n++ {
|
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
|
// go test -v -run=^$ -bench=UnsafeBytes -benchmem -count=4
|
||||||
|
|
||||||
func Benchmark_UnsafeBytes(b *testing.B) {
|
func Benchmark_UnsafeBytes(b *testing.B) {
|
||||||
var hello = "Hello, World!"
|
hello := "Hello, World!"
|
||||||
var res []byte
|
var res []byte
|
||||||
b.Run("unsafe", func(b *testing.B) {
|
b.Run("unsafe", func(b *testing.B) {
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
|
|
|
@ -6,7 +6,7 @@ package utils
|
||||||
|
|
||||||
// ToLower is the equivalent of strings.ToLower
|
// ToLower is the equivalent of strings.ToLower
|
||||||
func ToLower(b string) string {
|
func ToLower(b string) string {
|
||||||
var res = make([]byte, len(b))
|
res := make([]byte, len(b))
|
||||||
copy(res, b)
|
copy(res, b)
|
||||||
for i := 0; i < len(res); i++ {
|
for i := 0; i < len(res); i++ {
|
||||||
res[i] = toLowerTable[res[i]]
|
res[i] = toLowerTable[res[i]]
|
||||||
|
@ -17,7 +17,7 @@ func ToLower(b string) string {
|
||||||
|
|
||||||
// ToUpper is the equivalent of strings.ToUpper
|
// ToUpper is the equivalent of strings.ToUpper
|
||||||
func ToUpper(b string) string {
|
func ToUpper(b string) string {
|
||||||
var res = make([]byte, len(b))
|
res := make([]byte, len(b))
|
||||||
copy(res, b)
|
copy(res, b)
|
||||||
for i := 0; i < len(res); i++ {
|
for i := 0; i < len(res); i++ {
|
||||||
res[i] = toUpperTable[res[i]]
|
res[i] = toUpperTable[res[i]]
|
||||||
|
|
|
@ -16,7 +16,7 @@ func Test_ToUpper(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_ToUpper(b *testing.B) {
|
func Benchmark_ToUpper(b *testing.B) {
|
||||||
var path = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
path := "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
||||||
var res string
|
var res string
|
||||||
|
|
||||||
b.Run("fiber", func(b *testing.B) {
|
b.Run("fiber", func(b *testing.B) {
|
||||||
|
@ -48,7 +48,7 @@ func Test_ToLower(t *testing.T) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_ToLower(b *testing.B) {
|
func Benchmark_ToLower(b *testing.B) {
|
||||||
var path = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
path := "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
||||||
var res string
|
var res string
|
||||||
b.Run("fiber", func(b *testing.B) {
|
b.Run("fiber", func(b *testing.B) {
|
||||||
for n := 0; n < b.N; n++ {
|
for n := 0; n < b.N; n++ {
|
||||||
|
@ -72,6 +72,7 @@ func Test_TrimRight(t *testing.T) {
|
||||||
res = TrimRight("/test", '/')
|
res = TrimRight("/test", '/')
|
||||||
AssertEqual(t, "/test", res)
|
AssertEqual(t, "/test", res)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_TrimRight(b *testing.B) {
|
func Benchmark_TrimRight(b *testing.B) {
|
||||||
var res string
|
var res string
|
||||||
|
|
||||||
|
@ -97,6 +98,7 @@ func Test_TrimLeft(t *testing.T) {
|
||||||
res = TrimLeft("test/", '/')
|
res = TrimLeft("test/", '/')
|
||||||
AssertEqual(t, "test/", res)
|
AssertEqual(t, "test/", res)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Benchmark_TrimLeft(b *testing.B) {
|
func Benchmark_TrimLeft(b *testing.B) {
|
||||||
var res string
|
var res string
|
||||||
|
|
||||||
|
@ -113,6 +115,7 @@ func Benchmark_TrimLeft(b *testing.B) {
|
||||||
AssertEqual(b, "foobar", res)
|
AssertEqual(b, "foobar", res)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_Trim(t *testing.T) {
|
func Test_Trim(t *testing.T) {
|
||||||
t.Parallel()
|
t.Parallel()
|
||||||
res := Trim(" test ", ' ')
|
res := Trim(" test ", ' ')
|
||||||
|
@ -150,8 +153,8 @@ func Benchmark_Trim(b *testing.B) {
|
||||||
|
|
||||||
// go test -v -run=^$ -bench=Benchmark_EqualFold -benchmem -count=4
|
// go test -v -run=^$ -bench=Benchmark_EqualFold -benchmem -count=4
|
||||||
func Benchmark_EqualFold(b *testing.B) {
|
func Benchmark_EqualFold(b *testing.B) {
|
||||||
var left = "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
left := "/RePos/GoFiBer/FibEr/iSsues/187643/CoMmEnts"
|
||||||
var right = "/RePos/goFiber/Fiber/issues/187643/COMMENTS"
|
right := "/RePos/goFiber/Fiber/issues/187643/COMMENTS"
|
||||||
var res bool
|
var res bool
|
||||||
|
|
||||||
b.Run("fiber", func(b *testing.B) {
|
b.Run("fiber", func(b *testing.B) {
|
||||||
|
|
Loading…
Reference in New Issue