1
0
mirror of https://github.com/gofiber/fiber.git synced 2025-02-06 17:11:33 +00:00

👷 v3 (ci): fix some linter warnings

This commit is contained in:
Muhammed Efe Çetin 2023-02-09 22:33:45 +03:00
parent 7899176d8e
commit c2749c36c2
No known key found for this signature in database
GPG Key ID: 0AA4D45CBAA86F73
28 changed files with 107 additions and 99 deletions

2
app.go
View File

@ -1044,6 +1044,8 @@ func (app *App) serverErrorHandler(fctx *fasthttp.RequestCtx, err error) {
c := app.AcquireCtx().(*DefaultCtx)
c.Reset(fctx)
defer app.ReleaseCtx(c)
var errNetOP *net.OpError
switch {

View File

@ -605,17 +605,23 @@ func Test_App_Order(t *testing.T) {
app := New()
app.Get("/test", func(c Ctx) error {
c.Write([]byte("1"))
_, err := c.Write([]byte("1"))
require.NoError(t, err)
return c.Next()
})
app.All("/test", func(c Ctx) error {
c.Write([]byte("2"))
_, err := c.Write([]byte("2"))
require.NoError(t, err)
return c.Next()
})
app.Use(func(c Ctx) error {
c.Write([]byte("3"))
_, err := c.Write([]byte("3"))
require.NoError(t, err)
return nil
})
@ -865,9 +871,9 @@ func Test_App_Static_Custom_CacheControl(t *testing.T) {
require.Equal(t, nil, err, "app.Test(req)")
require.Equal(t, "no-cache, no-store, must-revalidate", resp.Header.Get(HeaderCacheControl), "CacheControl Control")
normal_resp, normal_err := app.Test(httptest.NewRequest(MethodGet, "/config.yml", nil))
require.Equal(t, nil, normal_err, "app.Test(req)")
require.Equal(t, "", normal_resp.Header.Get(HeaderCacheControl), "CacheControl Control")
normalResp, normalErr := app.Test(httptest.NewRequest(MethodGet, "/config.yml", nil))
require.Equal(t, nil, normalErr, "app.Test(req)")
require.Equal(t, "", normalResp.Header.Get(HeaderCacheControl), "CacheControl Control")
}
// go test -run Test_App_Static_Download

12
bind.go
View File

@ -66,9 +66,9 @@ func (b *Bind) validateStruct(out any) error {
// NOTE: Should/Must is still valid for Custom binders.
func (b *Bind) Custom(name string, dest any) error {
binders := b.ctx.App().customBinders
for _, binder := range binders {
if binder.Name() == name {
return b.returnErr(binder.Parse(b.ctx, dest))
for _, customBinder := range binders {
if customBinder.Name() == name {
return b.returnErr(customBinder.Parse(b.ctx, dest))
}
}
@ -181,10 +181,10 @@ func (b *Bind) Body(out any) error {
// Check custom binders
binders := b.ctx.App().customBinders
for _, binder := range binders {
for _, mime := range binder.MIMETypes() {
for _, customBinder := range binders {
for _, mime := range customBinder.MIMETypes() {
if mime == ctype {
return b.returnErr(binder.Parse(b.ctx, out))
return b.returnErr(customBinder.Parse(b.ctx, out))
}
}
}

View File

@ -16,6 +16,8 @@ import (
"github.com/valyala/fasthttp"
)
const helloWorld = "hello world"
// go test -run Test_Bind_Query -v
func Test_Bind_Query(t *testing.T) {
t.Parallel()
@ -63,7 +65,7 @@ func Test_Bind_Query(t *testing.T) {
c.Request().URI().SetQueryString("id=1&name=tom&hobby=basketball,football&favouriteDrinks=milo,coke,pepsi&alloc=&no=1")
q2 := new(Query2)
q2.Bool = true
q2.Name = "hello world"
q2.Name = helloWorld
require.Nil(t, c.Bind().Query(q2))
require.Equal(t, "basketball,football", q2.Hobby)
require.True(t, q2.Bool)
@ -133,7 +135,7 @@ func Test_Bind_Query_Map(t *testing.T) {
func Test_Bind_Query_WithSetParserDecoder(t *testing.T) {
type NonRFCTime time.Time
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)
}
@ -142,7 +144,7 @@ func Test_Bind_Query_WithSetParserDecoder(t *testing.T) {
nonRFCTime := binder.ParserType{
Customtype: NonRFCTime{},
Converter: NonRFCConverter,
Converter: nonRFCConverter,
}
binder.SetParserDecoder(binder.ParserConfig{
@ -167,7 +169,6 @@ func Test_Bind_Query_WithSetParserDecoder(t *testing.T) {
c.Request().URI().SetQueryString("date=2021-04-10&title=CustomDateTest&Body=October")
require.Nil(t, c.Bind().Query(q))
fmt.Println(q.Date, "q.Date")
require.Equal(t, "CustomDateTest", q.Title)
date := fmt.Sprintf("%v", q.Date)
require.Equal(t, "{0 63753609600 <nil>}", date)
@ -336,7 +337,7 @@ func Test_Bind_Header(t *testing.T) {
h2 := new(Header2)
h2.Bool = true
h2.Name = "hello world"
h2.Name = helloWorld
require.Nil(t, c.Bind().Header(h2))
require.Equal(t, "go,fiber", h2.Hobby)
require.True(t, h2.Bool)
@ -388,7 +389,7 @@ func Test_Bind_Header_Map(t *testing.T) {
func Test_Bind_Header_WithSetParserDecoder(t *testing.T) {
type NonRFCTime time.Time
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)
}
@ -397,7 +398,7 @@ func Test_Bind_Header_WithSetParserDecoder(t *testing.T) {
nonRFCTime := binder.ParserType{
Customtype: NonRFCTime{},
Converter: NonRFCConverter,
Converter: nonRFCConverter,
}
binder.SetParserDecoder(binder.ParserConfig{
@ -425,7 +426,6 @@ func Test_Bind_Header_WithSetParserDecoder(t *testing.T) {
c.Request().Header.Add("Body", "October")
require.Nil(t, c.Bind().Header(r))
fmt.Println(r.Date, "q.Date")
require.Equal(t, "CustomDateTest", r.Title)
date := fmt.Sprintf("%v", r.Date)
require.Equal(t, "{0 63753609600 <nil>}", date)
@ -578,7 +578,7 @@ func Test_Bind_RespHeader(t *testing.T) {
h2 := new(Header2)
h2.Bool = true
h2.Name = "hello world"
h2.Name = helloWorld
require.Nil(t, c.Bind().RespHeader(h2))
require.Equal(t, "go,fiber", h2.Hobby)
require.True(t, h2.Bool)
@ -1214,7 +1214,7 @@ func Test_Bind_Cookie(t *testing.T) {
h2 := new(Cookie2)
h2.Bool = true
h2.Name = "hello world"
h2.Name = helloWorld
require.Nil(t, c.Bind().Cookie(h2))
require.Equal(t, "go,fiber", h2.Hobby)
require.True(t, h2.Bool)
@ -1266,7 +1266,7 @@ func Test_Bind_Cookie_Map(t *testing.T) {
func Test_Bind_Cookie_WithSetParserDecoder(t *testing.T) {
type NonRFCTime time.Time
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)
}
@ -1275,7 +1275,7 @@ func Test_Bind_Cookie_WithSetParserDecoder(t *testing.T) {
nonRFCTime := binder.ParserType{
Customtype: NonRFCTime{},
Converter: NonRFCConverter,
Converter: nonRFCConverter,
}
binder.SetParserDecoder(binder.ParserConfig{
@ -1303,7 +1303,6 @@ func Test_Bind_Cookie_WithSetParserDecoder(t *testing.T) {
c.Request().Header.SetCookie("Body", "October")
require.Nil(t, c.Bind().Cookie(r))
fmt.Println(r.Date, "q.Date")
require.Equal(t, "CustomDateTest", r.Title)
date := fmt.Sprintf("%v", r.Date)
require.Equal(t, "{0 63753609600 <nil>}", date)
@ -1456,15 +1455,15 @@ func Benchmark_Bind_Cookie_Map(b *testing.B) {
// custom binder for testing
type customBinder struct{}
func (b *customBinder) Name() string {
func (*customBinder) Name() string {
return "custom"
}
func (b *customBinder) MIMETypes() []string {
func (*customBinder) MIMETypes() []string {
return []string{"test", "test2"}
}
func (b *customBinder) Parse(c Ctx, out any) error {
func (*customBinder) Parse(c Ctx, out any) error {
return json.Unmarshal(c.Body(), out)
}
@ -1474,8 +1473,8 @@ func Test_Bind_CustomBinder(t *testing.T) {
c := app.NewCtx(&fasthttp.RequestCtx{})
// Register binder
binder := &customBinder{}
app.RegisterCustomBinder(binder)
customBinder := &customBinder{}
app.RegisterCustomBinder(customBinder)
type Demo struct {
Name string `json:"name"`
@ -1510,11 +1509,11 @@ func Test_Bind_Must(t *testing.T) {
// simple struct validator for testing
type structValidator struct{}
func (v *structValidator) Engine() any {
func (*structValidator) Engine() any {
return ""
}
func (v *structValidator) ValidateStruct(out any) error {
func (*structValidator) ValidateStruct(out any) error {
out = reflect.ValueOf(out).Elem().Interface()
sq := out.(simpleQuery)

View File

@ -11,11 +11,13 @@ var (
)
// Init default binders for Fiber
var HeaderBinder = &headerBinding{}
var RespHeaderBinder = &respHeaderBinding{}
var CookieBinder = &cookieBinding{}
var QueryBinder = &queryBinding{}
var FormBinder = &formBinding{}
var URIBinder = &uriBinding{}
var XMLBinder = &xmlBinding{}
var JSONBinder = &jsonBinding{}
var (
HeaderBinder = &headerBinding{}
RespHeaderBinder = &respHeaderBinding{}
CookieBinder = &cookieBinding{}
QueryBinder = &queryBinding{}
FormBinder = &formBinding{}
URIBinder = &uriBinding{}
XMLBinder = &xmlBinding{}
JSONBinder = &jsonBinding{}
)

View File

@ -34,7 +34,6 @@ func (b *cookieBinding) Bind(reqCtx *fasthttp.RequestCtx, out any) error {
} else {
data[k] = append(data[k], v)
}
})
if err != nil {

View File

@ -10,6 +10,6 @@ func (*jsonBinding) Name() string {
return "json"
}
func (b *jsonBinding) Bind(body []byte, jsonDecoder utils.JSONUnmarshal, out any) error {
func (*jsonBinding) Bind(body []byte, jsonDecoder utils.JSONUnmarshal, out any) error {
return jsonDecoder(body, out)
}

View File

@ -134,10 +134,9 @@ func parseParamSquareBrackets(k string) (string, error) {
kbytes := []byte(k)
for i, b := range kbytes {
if b == '[' && kbytes[i+1] != ']' {
if err := bb.WriteByte('.'); err != nil {
return "", err
return "", err //nolint:wrapchec
}
}
@ -146,7 +145,7 @@ func parseParamSquareBrackets(k string) (string, error) {
}
if err := bb.WriteByte(b); err != nil {
return "", err
return "", err //nolint:wrapchec
}
}

View File

@ -38,7 +38,6 @@ func (b *queryBinding) Bind(reqCtx *fasthttp.RequestCtx, out any) error {
} else {
data[k] = append(data[k], v)
}
})
if err != nil {

View File

@ -10,6 +10,6 @@ func (*xmlBinding) Name() string {
return "xml"
}
func (b *xmlBinding) Bind(body []byte, out any) error {
func (*xmlBinding) Bind(body []byte, out any) error {
return xml.Unmarshal(body, out)
}

6
ctx.go
View File

@ -1147,12 +1147,12 @@ func (c *DefaultCtx) Route() *Route {
}
// SaveFile saves any multipart file to disk.
func (c *DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error {
func (*DefaultCtx) SaveFile(fileheader *multipart.FileHeader, path string) error {
return fasthttp.SaveMultipartFile(fileheader, path)
}
// SaveFileToStorage saves any multipart file to an external storage system.
func (c *DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error {
func (*DefaultCtx) SaveFileToStorage(fileheader *multipart.FileHeader, path string, storage Storage) error {
file, err := fileheader.Open()
if err != nil {
return fmt.Errorf("failed to open: %w", err)
@ -1442,7 +1442,7 @@ func (c *DefaultCtx) IsProxyTrusted() bool {
}
// IsLocalHost will return true if address is a localhost address.
func (c *DefaultCtx) isLocalHost(address string) bool {
func (*DefaultCtx) isLocalHost(address string) bool {
localHosts := []string{"127.0.0.1", "0.0.0.0", "::1"}
for _, h := range localHosts {
if strings.Contains(address, h) {

View File

@ -185,7 +185,7 @@ type Ctx interface {
// Next executes the next method in the stack that matches the current route.
Next() (err error)
// RestartRouting instead of going to the next handler. This may be usefull after
// RestartRouting instead of going to the next handler. This may be useful after
// changing the request path. Note that handlers might be executed again.
RestartRouting() error

View File

@ -78,7 +78,7 @@ type customCtx struct {
DefaultCtx
}
func (c *customCtx) Params(key string, defaultValue ...string) string {
func (c *customCtx) Params(key string, defaultValue ...string) string { //nolint:revive
return "prefix_" + c.DefaultCtx.Params(key)
}
@ -97,7 +97,7 @@ func Test_Ctx_CustomCtx(t *testing.T) {
app.Get("/:id", func(c Ctx) error {
return c.SendString(c.Params("id"))
})
resp, err := app.Test(httptest.NewRequest("GET", "/v3", &bytes.Buffer{}))
resp, err := app.Test(httptest.NewRequest(MethodGet, "/v3", &bytes.Buffer{}))
require.NoError(t, err, "app.Test(req)")
body, err := io.ReadAll(resp.Body)
require.NoError(t, err, "io.ReadAll(resp.Body)")
@ -531,27 +531,32 @@ func Test_Ctx_Format(t *testing.T) {
c := app.NewCtx(&fasthttp.RequestCtx{})
c.Request().Header.Set(HeaderAccept, MIMETextPlain)
c.Format([]byte("Hello, World!"))
err := c.Format([]byte("Hello, World!"))
require.NoError(t, err)
require.Equal(t, "Hello, World!", string(c.Response().Body()))
c.Request().Header.Set(HeaderAccept, MIMETextHTML)
c.Format("Hello, World!")
err = c.Format("Hello, World!")
require.NoError(t, err)
require.Equal(t, "<p>Hello, World!</p>", string(c.Response().Body()))
c.Request().Header.Set(HeaderAccept, MIMEApplicationJSON)
c.Format("Hello, World!")
err = c.Format("Hello, World!")
require.NoError(t, err)
require.Equal(t, `"Hello, World!"`, string(c.Response().Body()))
c.Request().Header.Set(HeaderAccept, MIMETextPlain)
c.Format(complex(1, 1))
err = c.Format(complex(1, 1))
require.NoError(t, err)
require.Equal(t, "(1+1i)", string(c.Response().Body()))
c.Request().Header.Set(HeaderAccept, MIMEApplicationXML)
c.Format("Hello, World!")
err = c.Format("Hello, World!")
require.NoError(t, err)
require.Equal(t, `<string>Hello, World!</string>`, string(c.Response().Body()))
err := c.Format(complex(1, 1))
require.True(t, err != nil)
err = c.Format(complex(1, 1))
require.Error(t, err)
c.Request().Header.Set(HeaderAccept, MIMETextPlain)
c.Format(Map{})
@ -1079,7 +1084,7 @@ func Test_Ctx_IP(t *testing.T) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
// default behaviour will return the remote IP from the stack
// default behavior will return the remote IP from the stack
require.Equal(t, "0.0.0.0", c.IP())
// X-Forwarded-For is set, but it is ignored because proxyHeader is not set
@ -2569,11 +2574,12 @@ func Test_Ctx_RenderWithBindVars(t *testing.T) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
c.BindVars(Map{
err := c.BindVars(Map{
"Title": "Hello, World!",
})
require.NoError(t, err)
err := c.Render("./.github/testdata/index.tmpl", Map{})
err = c.Render("./.github/testdata/index.tmpl", Map{})
require.NoError(t, err)
buf := bytebufferpool.Get()
_, _ = buf.WriteString("overwrite") //nolint:errcheck // This will never fail
@ -2659,10 +2665,10 @@ func Benchmark_Ctx_RenderWithLocalsAndBindVars(b *testing.B) {
})
c := app.NewCtx(&fasthttp.RequestCtx{})
c.BindVars(Map{
err = c.BindVars(Map{
"Title": "Hello, World!",
})
require.Equal(b, nil, err)
require.NoError(b, err)
c.Locals("Summary", "Test")
b.ReportAllocs()
@ -2707,10 +2713,10 @@ func Benchmark_Ctx_RenderBindVars(b *testing.B) {
app.config.Views = engine
c := app.NewCtx(&fasthttp.RequestCtx{})
c.BindVars(Map{
err = c.BindVars(Map{
"Title": "Hello, World!",
})
require.Equal(b, nil, err)
require.NoError(b, err)
b.ReportAllocs()
b.ResetTimer()

1
go.mod
View File

@ -3,7 +3,6 @@ module github.com/gofiber/fiber/v3
go 1.20
require (
github.com/gofiber/fiber/v2 v2.40.1
github.com/gofiber/utils/v2 v2.0.0-beta.1
github.com/google/uuid v1.3.0
github.com/mattn/go-colorable v0.1.13

2
go.sum
View File

@ -3,8 +3,6 @@ github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHG
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gofiber/fiber/v2 v2.40.1 h1:pc7n9VVpGIqNsvg9IPLQhyFEMJL8gCs1kneH5D1pIl4=
github.com/gofiber/fiber/v2 v2.40.1/go.mod h1:Gko04sLksnHbzLSRBFWPFdzM9Ws9pRxvvIaohJK1dsk=
github.com/gofiber/utils/v2 v2.0.0-beta.1 h1:ACfPdqeclx+BFIja19UjkKx7k3r5tmpILpNgzrfPLKs=
github.com/gofiber/utils/v2 v2.0.0-beta.1/go.mod h1:CG89nDoIkEFIJaw5LdLO9AmBM11odse/LC79KQujm74=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=

View File

@ -118,7 +118,6 @@ func Test_Listen_TLS(t *testing.T) {
CertFile: "./.github/testdata/ssl.pem",
CertKeyFile: "./.github/testdata/ssl.key",
}))
}
// go test -run Test_Listen_TLS_Prefork
@ -146,7 +145,6 @@ func Test_Listen_TLS_Prefork(t *testing.T) {
CertFile: "./.github/testdata/ssl.pem",
CertKeyFile: "./.github/testdata/ssl.key",
}))
}
// go test -run Test_Listen_MutualTLS
@ -419,7 +417,7 @@ func Test_Listen_Print_Route(t *testing.T) {
app.printRoutesMessage()
})
fmt.Println(printRoutesMessage)
require.True(t, strings.Contains(printRoutesMessage, "GET"))
require.True(t, strings.Contains(printRoutesMessage, MethodGet))
require.True(t, strings.Contains(printRoutesMessage, "/"))
require.True(t, strings.Contains(printRoutesMessage, "emptyHandler"))
require.True(t, strings.Contains(printRoutesMessage, "routeName"))
@ -439,7 +437,7 @@ func Test_Listen_Print_Route_With_Group(t *testing.T) {
app.printRoutesMessage()
})
require.True(t, strings.Contains(printRoutesMessage, "GET"))
require.True(t, strings.Contains(printRoutesMessage, MethodGet))
require.True(t, strings.Contains(printRoutesMessage, "/"))
require.True(t, strings.Contains(printRoutesMessage, "emptyHandler"))
require.True(t, strings.Contains(printRoutesMessage, "/v1/test"))

View File

@ -141,7 +141,6 @@ func Test_HTTPHandler(t *testing.T) {
}
func Test_HTTPMiddleware(t *testing.T) {
tests := []struct {
name string
url string

View File

@ -21,7 +21,7 @@ func Test_Default(t *testing.T) {
return c.SendString("Hello, World!")
})
resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, "1; mode=block", resp.Header.Get(fiber.HeaderXXSSProtection))
require.Equal(t, "nosniff", resp.Header.Get(fiber.HeaderXContentTypeOptions))
@ -48,11 +48,11 @@ func Test_Filter(t *testing.T) {
return c.SendString("Skipped!")
})
resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, "no-referrer", resp.Header.Get(fiber.HeaderReferrerPolicy))
resp, err = app.Test(httptest.NewRequest("GET", "/filter", nil))
resp, err = app.Test(httptest.NewRequest(fiber.MethodGet, "/filter", nil))
require.NoError(t, err)
require.Equal(t, "", resp.Header.Get(fiber.HeaderReferrerPolicy))
}
@ -68,7 +68,7 @@ func Test_ContentSecurityPolicy(t *testing.T) {
return c.SendString("Hello, World!")
})
resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, "default-src 'none'", resp.Header.Get(fiber.HeaderContentSecurityPolicy))
}
@ -85,7 +85,7 @@ func Test_ContentSecurityPolicyReportOnly(t *testing.T) {
return c.SendString("Hello, World!")
})
resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, "default-src 'none'", resp.Header.Get(fiber.HeaderContentSecurityPolicyReportOnly))
require.Equal(t, "", resp.Header.Get(fiber.HeaderContentSecurityPolicy))
@ -102,7 +102,7 @@ func Test_PermissionsPolicy(t *testing.T) {
return c.SendString("Hello, World!")
})
resp, err := app.Test(httptest.NewRequest("GET", "/", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/", nil))
require.NoError(t, err)
require.Equal(t, "microphone=()", resp.Header.Get(fiber.HeaderPermissionsPolicy))
}

View File

@ -69,7 +69,7 @@ func New(config ...Config) fiber.Handler {
}
if cfg.ErrorHandler == nil {
cfg.ErrorHandler = func(c fiber.Ctx, err error) error {
if err == ErrMissingOrMalformedAPIKey {
if errors.Is(err, ErrMissingOrMalformedAPIKey) {
return c.Status(fiber.StatusBadRequest).SendString(err.Error())
}
return c.Status(fiber.StatusUnauthorized).SendString("Invalid or expired API Key")

View File

@ -6,8 +6,8 @@ import (
"sync"
"time"
"github.com/gofiber/fiber/v2/utils"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/utils/v2"
"github.com/mattn/go-colorable"
"github.com/mattn/go-isatty"
"github.com/valyala/bytebufferpool"

View File

@ -4,7 +4,7 @@ import (
"bytes"
"errors"
"github.com/gofiber/fiber/v2/utils"
"github.com/gofiber/utils/v2"
)
// buildLogFuncChain analyzes the template and creates slices with the functions for execution and

View File

@ -48,7 +48,7 @@ func New(config ...Config) fiber.Handler {
// Initialize
for k, v := range cfg.Rules {
k = strings.Replace(k, "*", "(.*)", -1)
k = k + "$"
k += "$"
cfg.rulesRegex[regexp.MustCompile(k)] = v
}
// Middleware function

View File

@ -1,3 +1,4 @@
//nolint:bodyclose // Much easier to just ignore memory leaks in tests
// 🚀 Fiber is an Express inspired web framework written in Go with 💖
// 📌 API Documentation: https://fiber.wiki
// 📝 Github Repository: https://github.com/gofiber/fiber
@ -9,6 +10,7 @@ import (
"testing"
"github.com/gofiber/fiber/v3"
"github.com/stretchr/testify/require"
)
func Test_Redirect(t *testing.T) {
@ -108,7 +110,8 @@ func Test_Redirect(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, _ := http.NewRequest("GET", tt.url, nil)
req, err := http.NewRequest(fiber.MethodGet, tt.url, nil)
require.NoError(t, err)
req.Header.Set("Location", "github.com/gofiber/redirect")
resp, err := app.Test(req)
if err != nil {
@ -122,5 +125,4 @@ func Test_Redirect(t *testing.T) {
}
})
}
}

View File

@ -51,7 +51,7 @@ func New(config ...Config) fiber.Handler {
// Initialize
for k, v := range cfg.Rules {
k = strings.Replace(k, "*", "(.*)", -1)
k = k + "$"
k += "$"
cfg.rulesRegex[regexp.MustCompile(k)] = v
}
// Middleware function

View File

@ -359,7 +359,8 @@ func Test_Session_Reset(t *testing.T) {
// set value & save
sess.Set("name", "fenny")
require.NoError(t, sess.Save())
sess, _ = store.Get(ctx)
sess, err = store.Get(ctx)
require.NoError(t, err)
err = sess.Destroy()
require.NoError(t, err)

View File

@ -287,7 +287,7 @@ func (r *Redirect) setFlash() {
r.c.ClearCookie(FlashCookieName)
}
func parseMessage(raw string) (key, value string) {
func parseMessage(raw string) (string, string) {
if i := findNextNonEscapedCharsetPosition(raw, []byte(CookieDataAssigner)); i != -1 {
return RemoveEscapeChar(raw[:i]), RemoveEscapeChar(raw[i+1:])
}

View File

@ -96,7 +96,7 @@ func (r *Route) match(detectionPath, path string, params *[maxParams]string) boo
return false
}
func (app *App) nextCustom(c CustomCtx) (match bool, err error) {
func (app *App) nextCustom(c CustomCtx) (bool, error) {
// Get stack length
tree, ok := app.treeStack[c.getMethodINT()][c.getTreePath()]
if !ok {
@ -113,7 +113,7 @@ func (app *App) nextCustom(c CustomCtx) (match bool, err error) {
route := tree[c.getIndexRoute()]
// Check if it matches the request path
match = route.match(c.getDetectionPath(), c.Path(), c.getValues())
match := route.match(c.getDetectionPath(), c.Path(), c.getValues())
// No match, next route
if !match {
@ -129,22 +129,22 @@ func (app *App) nextCustom(c CustomCtx) (match bool, err error) {
// Execute first handler of route
c.setIndexHandler(0)
err = route.Handlers[0](c)
err := route.Handlers[0](c)
return match, err // Stop scanning the stack
}
// If c.Next() does not match, return 404
err = NewError(StatusNotFound, "Cannot "+c.Method()+" "+c.getPathOriginal())
err := NewError(StatusNotFound, "Cannot "+c.Method()+" "+c.getPathOriginal())
// If no match, scan stack again if other methods match the request
// Moved from app.handler because middleware may break the route chain
if !c.getMatched() && app.methodExistCustom(c) {
err = ErrMethodNotAllowed
}
return
return false, err
}
func (app *App) next(c *DefaultCtx) (match bool, err error) {
func (app *App) next(c *DefaultCtx) (bool, error) {
// Get stack length
tree, ok := app.treeStack[c.methodINT][c.treePath]
if !ok {
@ -181,7 +181,7 @@ func (app *App) next(c *DefaultCtx) (match bool, err error) {
}
// If c.Next() does not match, return 404
err = NewError(StatusNotFound, "Cannot "+c.method+" "+c.pathOriginal)
err := NewError(StatusNotFound, "Cannot "+c.method+" "+c.pathOriginal)
if !c.matched && app.methodExist(c) {
// If no match, scan stack again if other methods match the request
// Moved from app.handler because middleware may break the route chain
@ -274,7 +274,6 @@ func (app *App) register(methods []string, pathRaw string, group *Group, handler
}
for _, method := range methods {
// Uppercase HTTP methods
method = utils.ToUpper(method)
// Check if the HTTP method is valid unless it's USE

View File

@ -489,7 +489,7 @@ func Benchmark_App_MethodNotAllowed(b *testing.B) {
}
b.StopTimer()
require.Equal(b, 405, c.Response.StatusCode())
require.Equal(b, "GET", string(c.Response.Header.Peek("Allow")))
require.Equal(b, MethodGet, string(c.Response.Header.Peek("Allow")))
require.Equal(b, utils.StatusMessage(StatusMethodNotAllowed), string(c.Response.Body()))
}