👷 v3 (ci): fix some linter warnings

pull/2538/head
Muhammed Efe Çetin 2023-03-06 17:35:39 +03:00
parent 3168a60605
commit 41866cd3dd
No known key found for this signature in database
GPG Key ID: 0AA4D45CBAA86F73
32 changed files with 237 additions and 143 deletions

View File

@ -1,6 +1,8 @@
package retry
import "time"
import (
"time"
)
// Config defines the config for addon.
type Config struct {

9
app.go
View File

@ -821,7 +821,7 @@ func (app *App) Config() Config {
func (app *App) Handler() fasthttp.RequestHandler { //revive:disable-line:confusing-naming // Having both a Handler() (uppercase) and a handler() (lowercase) is fine. TODO: Use nolint:revive directive instead. See https://github.com/golangci/golangci-lint/issues/3476
// prepare the server for the start
app.startupProcess()
return app.handler
return app.requestHandler
}
// Stack returns the raw router stack.
@ -981,7 +981,7 @@ func (app *App) init() *App {
}
// fasthttp server settings
app.server.Handler = app.handler
app.server.Handler = app.requestHandler
app.server.Name = app.config.ServerHeader
app.server.Concurrency = app.config.Concurrency
app.server.NoDefaultDate = app.config.DisableDefaultDate
@ -1041,7 +1041,10 @@ func (app *App) ErrorHandler(ctx Ctx, err error) error {
// errors before calling the application's error handler method.
func (app *App) serverErrorHandler(fctx *fasthttp.RequestCtx, err error) {
// Acquire Ctx with fasthttp request from pool
c := app.AcquireCtx().(*DefaultCtx)
c, ok := app.AcquireCtx().(*DefaultCtx)
if !ok {
panic(fmt.Errorf("failed to type-assert to *DefaultCtx"))
}
c.Reset(fctx)
defer app.ReleaseCtx(c)

View File

@ -257,7 +257,7 @@ func Test_App_serverErrorHandler_Internal_Error(t *testing.T) {
t.Parallel()
app := New()
msg := "test err"
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
app.serverErrorHandler(c.fasthttp, errors.New(msg))
require.Equal(t, string(c.fasthttp.Response.Body()), msg)
@ -1294,7 +1294,7 @@ func Benchmark_AcquireCtx(b *testing.B) {
// go test -v -run=^$ -bench=Benchmark_NewError -benchmem -count=4
func Benchmark_NewError(b *testing.B) {
for n := 0; n < b.N; n++ {
NewError(200, "test")
NewError(200, "test") //nolint:errcheck // not needed
}
}

View File

@ -1,3 +1,4 @@
//nolint:wrapcheck,tagliatelle,bodyclose // We must not wrap errors in tests
package fiber
import (
@ -628,6 +629,8 @@ func Test_Bind_RespHeader_Map(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Bind_Query -benchmem -count=4
func Benchmark_Bind_Query(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -643,13 +646,15 @@ func Benchmark_Bind_Query(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Query(q)
err = c.Bind().Query(q)
}
require.Nil(b, c.Bind().Query(q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Query_Map -benchmem -count=4
func Benchmark_Bind_Query_Map(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -660,13 +665,15 @@ func Benchmark_Bind_Query_Map(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Query(&q)
err = c.Bind().Query(&q)
}
require.Nil(b, c.Bind().Query(&q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Query_WithParseParam -benchmem -count=4
func Benchmark_Bind_Query_WithParseParam(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -687,14 +694,16 @@ func Benchmark_Bind_Query_WithParseParam(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Query(cq)
err = c.Bind().Query(cq)
}
require.Nil(b, c.Bind().Query(cq))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Query_Comma -benchmem -count=4
func Benchmark_Bind_Query_Comma(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -711,13 +720,15 @@ func Benchmark_Bind_Query_Comma(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Query(q)
err = c.Bind().Query(q)
}
require.Nil(b, c.Bind().Query(q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Header -benchmem -count=4
func Benchmark_Bind_Header(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -737,13 +748,14 @@ func Benchmark_Bind_Header(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Header(q)
err = c.Bind().Header(q)
}
require.Nil(b, c.Bind().Header(q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Header_Map -benchmem -count=4
func Benchmark_Bind_Header_Map(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -758,13 +770,15 @@ func Benchmark_Bind_Header_Map(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Header(&q)
err = c.Bind().Header(&q)
}
require.Nil(b, c.Bind().Header(&q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_RespHeader -benchmem -count=4
func Benchmark_Bind_RespHeader(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -784,13 +798,14 @@ func Benchmark_Bind_RespHeader(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().RespHeader(q)
err = c.Bind().RespHeader(q)
}
require.Nil(b, c.Bind().RespHeader(q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_RespHeader_Map -benchmem -count=4
func Benchmark_Bind_RespHeader_Map(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -805,9 +820,9 @@ func Benchmark_Bind_RespHeader_Map(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().RespHeader(&q)
err = c.Bind().RespHeader(&q)
}
require.Nil(b, c.Bind().RespHeader(&q))
require.Nil(b, err)
}
// go test -run Test_Bind_Body
@ -823,8 +838,10 @@ func Test_Bind_Body(t *testing.T) {
{
var gzipJSON bytes.Buffer
w := gzip.NewWriter(&gzipJSON)
_, _ = w.Write([]byte(`{"name":"john"}`))
_ = w.Close()
_, err := w.Write([]byte(`{"name":"john"}`))
require.NoError(t, err)
err = w.Close()
require.NoError(t, err)
c.Request().Header.SetContentType(MIMEApplicationJSON)
c.Request().Header.Set(HeaderContentEncoding, "gzip")
@ -938,6 +955,8 @@ func Test_Bind_Body_WithSetParserDecoder(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Bind_Body_JSON -benchmem -count=4
func Benchmark_Bind_Body_JSON(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -954,14 +973,16 @@ func Benchmark_Bind_Body_JSON(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = c.Bind().Body(d)
err = c.Bind().Body(d)
}
require.Nil(b, c.Bind().Body(d))
require.Nil(b, err)
require.Equal(b, "john", d.Name)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Body_XML -benchmem -count=4
func Benchmark_Bind_Body_XML(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -978,14 +999,16 @@ func Benchmark_Bind_Body_XML(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = c.Bind().Body(d)
err = c.Bind().Body(d)
}
require.Nil(b, c.Bind().Body(d))
require.Nil(b, err)
require.Equal(b, "john", d.Name)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Body_Form -benchmem -count=4
func Benchmark_Bind_Body_Form(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -1002,14 +1025,16 @@ func Benchmark_Bind_Body_Form(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = c.Bind().Body(d)
err = c.Bind().Body(d)
}
require.Nil(b, c.Bind().Body(d))
require.Nil(b, err)
require.Equal(b, "john", d.Name)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Body_MultipartForm -benchmem -count=4
func Benchmark_Bind_Body_MultipartForm(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -1027,14 +1052,16 @@ func Benchmark_Bind_Body_MultipartForm(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = c.Bind().Body(d)
err = c.Bind().Body(d)
}
require.Nil(b, c.Bind().Body(d))
require.Nil(b, err)
require.Equal(b, "john", d.Name)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Body_Form_Map -benchmem -count=4
func Benchmark_Bind_Body_Form_Map(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -1048,9 +1075,9 @@ func Benchmark_Bind_Body_Form_Map(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = c.Bind().Body(&d)
err = c.Bind().Body(&d)
}
require.Nil(b, c.Bind().Body(&d))
require.Nil(b, err)
require.Equal(b, "john", d["name"])
}
@ -1064,9 +1091,7 @@ func Test_Bind_URI(t *testing.T) {
UserID uint `uri:"userId"`
RoleID uint `uri:"roleId"`
}
var (
d = new(Demo)
)
d := new(Demo)
if err := c.Bind().URI(d); err != nil {
t.Fatal(err)
}
@ -1074,8 +1099,10 @@ func Test_Bind_URI(t *testing.T) {
require.Equal(t, uint(222), d.RoleID)
return nil
})
app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil))
app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil))
_, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil))
require.NoError(t, err)
_, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil))
require.NoError(t, err)
}
// go test -run Test_Bind_URI_Map
@ -1093,14 +1120,18 @@ func Test_Bind_URI_Map(t *testing.T) {
require.Equal(t, uint(222), d["roleId"])
return nil
})
app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil))
app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil))
_, err := app.Test(httptest.NewRequest(MethodGet, "/test1/111/role/222", nil))
require.NoError(t, err)
_, err = app.Test(httptest.NewRequest(MethodGet, "/test2/111/role/222", nil))
require.NoError(t, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_URI -benchmem -count=4
func Benchmark_Bind_URI(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.route = &Route{
Params: []string{
@ -1122,9 +1153,10 @@ func Benchmark_Bind_URI(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().URI(&res)
err = c.Bind().URI(&res)
}
require.NoError(b, err)
require.Equal(b, "john", res.Param1)
require.Equal(b, "doe", res.Param2)
require.Equal(b, "is", res.Param3)
@ -1133,8 +1165,10 @@ func Benchmark_Bind_URI(b *testing.B) {
// go test -v -run=^$ -bench=Benchmark_Bind_URI_Map -benchmem -count=4
func Benchmark_Bind_URI_Map(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.route = &Route{
Params: []string{
@ -1151,9 +1185,10 @@ func Benchmark_Bind_URI_Map(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().URI(&res)
err = c.Bind().URI(&res)
}
require.NoError(b, err)
require.Equal(b, "john", res["param1"])
require.Equal(b, "doe", res["param2"])
require.Equal(b, "is", res["param3"])
@ -1405,6 +1440,8 @@ func Test_Bind_Cookie_Schema(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Bind_Cookie -benchmem -count=4
func Benchmark_Bind_Cookie(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -1425,13 +1462,15 @@ func Benchmark_Bind_Cookie(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Cookie(q)
err = c.Bind().Cookie(q)
}
require.Nil(b, c.Bind().Cookie(q))
require.Nil(b, err)
}
// go test -v -run=^$ -bench=Benchmark_Bind_Cookie_Map -benchmem -count=4
func Benchmark_Bind_Cookie_Map(b *testing.B) {
var err error
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
@ -1447,9 +1486,9 @@ func Benchmark_Bind_Cookie_Map(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Bind().Cookie(&q)
err = c.Bind().Cookie(&q)
}
require.Nil(b, c.Bind().Cookie(&q))
require.Nil(b, err)
}
// custom binder for testing
@ -1515,10 +1554,13 @@ func (*structValidator) Engine() any {
func (*structValidator) ValidateStruct(out any) error {
out = reflect.ValueOf(out).Elem().Interface()
sq := out.(simpleQuery)
sq, ok := out.(simpleQuery)
if !ok {
return fmt.Errorf("failed to type-assert to simpleQuery")
}
if sq.Name != "john" {
return errors.New("you should have entered right name!")
return errors.New("you should have entered right name")
}
return nil
@ -1567,8 +1609,10 @@ func Test_Bind_RepeatParserWithSameStruct(t *testing.T) {
var gzipJSON bytes.Buffer
w := gzip.NewWriter(&gzipJSON)
_, _ = w.Write([]byte(`{"body_param":"body_param"}`))
_ = w.Close()
_, err := w.Write([]byte(`{"body_param":"body_param"}`))
require.NoError(t, err)
err = w.Close()
require.NoError(t, err)
c.Request().Header.SetContentType(MIMEApplicationJSON)
c.Request().Header.Set(HeaderContentEncoding, "gzip")
c.Request().SetBody(gzipJSON.Bytes())

View File

@ -86,7 +86,7 @@ func parse(aliasTag string, out any, data map[string][]string) error {
// Parse data into the struct with gorilla/schema
func parseToStruct(aliasTag string, out any, data map[string][]string) error {
// Get decoder from pool
schemaDecoder := decoderPoolMap[aliasTag].Get().(*schema.Decoder)
schemaDecoder := decoderPoolMap[aliasTag].Get().(*schema.Decoder) //nolint:errcheck,forcetypeassert // not needed
defer decoderPoolMap[aliasTag].Put(schemaDecoder)
// Set alias tag
@ -136,7 +136,7 @@ func parseParamSquareBrackets(k string) (string, error) {
for i, b := range kbytes {
if b == '[' && kbytes[i+1] != ']' {
if err := bb.WriteByte('.'); err != nil {
return "", err //nolint:wrapchec
return "", err //nolint:wrapchec,wrapcheck // unnecessary to wrap it
}
}
@ -145,7 +145,7 @@ func parseParamSquareBrackets(k string) (string, error) {
}
if err := bb.WriteByte(b); err != nil {
return "", err //nolint:wrapchec
return "", err //nolint:wrapchec,wrapcheck // unnecessary to wrap it
}
}

View File

@ -2,6 +2,7 @@ package binder
import (
"encoding/xml"
"fmt"
)
type xmlBinding struct{}
@ -11,5 +12,9 @@ func (*xmlBinding) Name() string {
}
func (*xmlBinding) Bind(body []byte, out any) error {
return xml.Unmarshal(body, out)
if err := xml.Unmarshal(body, out); err != nil {
return fmt.Errorf("failed to unmarshal xml: %w", err)
}
return nil
}

View File

@ -5,6 +5,7 @@ import (
"bytes"
"crypto/tls"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
@ -17,8 +18,6 @@ import (
"testing"
"time"
"encoding/json"
"github.com/gofiber/fiber/v3/internal/tlstest"
"github.com/stretchr/testify/require"
"github.com/valyala/fasthttp/fasthttputil"

6
ctx.go
View File

@ -1109,7 +1109,11 @@ func (c *DefaultCtx) Render(name string, bind Map, layouts ...string) error {
func (c *DefaultCtx) renderExtensions(bind Map) {
// Bind view map
c.viewBindMap.Range(func(key, value any) bool {
bind[key.(string)] = value
keyS, ok := key.(string)
if !ok {
panic(fmt.Errorf("failed to type-assert to string"))
}
bind[keyS] = value
return true
})

View File

@ -7,6 +7,7 @@ package fiber
import (
"context"
"crypto/tls"
"fmt"
"io"
"mime/multipart"
"sync"
@ -408,7 +409,11 @@ func (app *App) NewCtx(fctx *fasthttp.RequestCtx) Ctx {
// AcquireCtx retrieves a new Ctx from the pool.
func (app *App) AcquireCtx() Ctx {
return app.pool.Get().(Ctx)
ctx, ok := app.pool.Get().(Ctx)
if !ok {
panic(fmt.Errorf("failed to type-assert to Ctx"))
}
return ctx
}
// ReleaseCtx releases the ctx back into the pool.

View File

@ -62,7 +62,7 @@ func Test_Ctx_Accepts(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Accepts -benchmem -count=4
func Benchmark_Ctx_Accepts(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9")
var res string
@ -78,7 +78,7 @@ type customCtx struct {
DefaultCtx
}
func (c *customCtx) Params(key string, defaultValue ...string) string { //nolint:revive
func (c *customCtx) Params(key string, defaultValue ...string) string { //revive:disable-line:unused-parameter // We need defaultValue for some cases
return "prefix_" + c.DefaultCtx.Params(key)
}
@ -140,7 +140,7 @@ func Test_Ctx_AcceptsCharsets(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_AcceptsCharsets -benchmem -count=4
func Benchmark_Ctx_AcceptsCharsets(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set("Accept-Charset", "utf-8, iso-8859-1;q=0.5")
var res string
@ -166,7 +166,7 @@ func Test_Ctx_AcceptsEncodings(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_AcceptsEncodings -benchmem -count=4
func Benchmark_Ctx_AcceptsEncodings(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set(HeaderAcceptEncoding, "deflate, gzip;q=1.0, *;q=0.5")
var res string
@ -191,7 +191,7 @@ func Test_Ctx_AcceptsLanguages(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_AcceptsLanguages -benchmem -count=4
func Benchmark_Ctx_AcceptsLanguages(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set(HeaderAcceptLanguage, "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5")
var res string
@ -252,7 +252,7 @@ func Test_Ctx_Append(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Append -benchmem -count=4
func Benchmark_Ctx_Append(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
b.ReportAllocs()
b.ResetTimer()
@ -285,7 +285,7 @@ func Test_Ctx_Attachment(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Attachment -benchmem -count=4
func Benchmark_Ctx_Attachment(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
b.ReportAllocs()
b.ResetTimer()
@ -311,7 +311,7 @@ func Test_Ctx_BaseURL(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_BaseURL -benchmem
func Benchmark_Ctx_BaseURL(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
c.Request().SetHost("google.com:1337")
c.Request().URI().SetPath("/haha/oke/lol")
@ -500,7 +500,7 @@ func Test_Ctx_Cookie(t *testing.T) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Cookie -benchmem -count=4
func Benchmark_Ctx_Cookie(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx)
c := app.NewCtx(&fasthttp.RequestCtx{}).(*DefaultCtx) //nolint:errcheck, forcetypeassert // not needed
b.ReportAllocs()
b.ResetTimer()
@ -591,7 +591,7 @@ func Benchmark_Ctx_Format(b *testing.B) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Format_HTML -benchmem -count=4
func Benchmark_Ctx_Format_HTML(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
c := app.NewCtx(&fasthttp.RequestCtx{}) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set("Accept", "text/html")
b.ReportAllocs()
@ -608,7 +608,7 @@ func Benchmark_Ctx_Format_HTML(b *testing.B) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Format_JSON -benchmem -count=4
func Benchmark_Ctx_Format_JSON(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
c := app.NewCtx(&fasthttp.RequestCtx{}) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set("Accept", "application/json")
b.ReportAllocs()
@ -625,7 +625,7 @@ func Benchmark_Ctx_Format_JSON(b *testing.B) {
// go test -v -run=^$ -bench=Benchmark_Ctx_Format_XML -benchmem -count=4
func Benchmark_Ctx_Format_XML(b *testing.B) {
app := New()
c := app.NewCtx(&fasthttp.RequestCtx{})
c := app.NewCtx(&fasthttp.RequestCtx{}) //nolint:errcheck, forcetypeassert // not needed
c.Request().Header.Set("Accept", "application/xml")
b.ReportAllocs()

View File

@ -12,7 +12,7 @@ import (
func Test_Memory(t *testing.T) {
t.Parallel()
var store = New()
store := New()
var (
key = "john"
val any = []byte("doe")
@ -76,7 +76,6 @@ func Benchmark_Memory(b *testing.B) {
}
for _, key := range keys {
d.Delete(key)
}
}
})

View File

@ -65,9 +65,7 @@ func Test_Storage_Memory_Set_Expiration(t *testing.T) {
}
func Test_Storage_Memory_Get_Expired(t *testing.T) {
var (
key = "john"
)
key := "john"
result, err := testStore.Get(key)
require.NoError(t, err)
@ -102,9 +100,7 @@ func Test_Storage_Memory_Delete(t *testing.T) {
func Test_Storage_Memory_Reset(t *testing.T) {
t.Parallel()
var (
val = []byte("doe")
)
val := []byte("doe")
err := testStore.Set("john1", val, 0)
require.NoError(t, err)

View File

@ -63,7 +63,7 @@ type ListenConfig struct {
// GracefulContext is a field to shutdown Fiber by given context gracefully.
//
// Default: nil
GracefulContext context.Context `json:"graceful_context"`
GracefulContext context.Context `json:"graceful_context"` //nolint:containedctx // It's needed to set context inside Listen.
// TLSConfigFunc allows customizing tls.Config as you want.
//
@ -112,7 +112,7 @@ func listenConfigDefault(config ...ListenConfig) ListenConfig {
return ListenConfig{
ListenerNetwork: NetworkTCP4,
OnShutdownError: func(err error) {
log.Fatalf("shutdown: %v", err)
log.Fatalf("shutdown: %v", err) //nolint:revive // It's an optipn
},
}
}
@ -124,7 +124,7 @@ func listenConfigDefault(config ...ListenConfig) ListenConfig {
if cfg.OnShutdownError == nil {
cfg.OnShutdownError = func(err error) {
log.Fatalf("shutdown: %v", err)
log.Fatalf("shutdown: %v", err) //nolint:revive // It's an optipn
}
}
@ -141,7 +141,7 @@ func (app *App) Listen(addr string, config ...ListenConfig) error {
cfg := listenConfigDefault(config...)
// Configure TLS
var tlsConfig *tls.Config = nil
var tlsConfig *tls.Config
if cfg.CertFile != "" && cfg.CertKeyFile != "" {
cert, err := tls.LoadX509KeyPair(cfg.CertFile, cfg.CertKeyFile)
if err != nil {
@ -160,7 +160,7 @@ func (app *App) Listen(addr string, config ...ListenConfig) error {
if cfg.CertClientFile != "" {
clientCACert, err := os.ReadFile(filepath.Clean(cfg.CertClientFile))
if err != nil {
return err
return fmt.Errorf("failed to read file: %w", err)
}
clientCertPool := x509.NewCertPool()
@ -248,7 +248,7 @@ func (app *App) Listener(ln net.Listener, config ...ListenConfig) error {
}
// Create listener function.
func (app *App) createListener(addr string, tlsConfig *tls.Config, cfg ListenConfig) (net.Listener, error) {
func (*App) createListener(addr string, tlsConfig *tls.Config, cfg ListenConfig) (net.Listener, error) {
var listener net.Listener
var err error
@ -262,6 +262,11 @@ func (app *App) createListener(addr string, tlsConfig *tls.Config, cfg ListenCon
cfg.ListenerAddrFunc(listener.Addr())
}
// Wrap error comes from tls.Listen/net.Listen
if err != nil {
err = fmt.Errorf("failed to listen: %w", err)
}
return listener, err
}
@ -278,7 +283,7 @@ func (app *App) printMessages(cfg ListenConfig, ln net.Listener) {
}
// startupMessage prepares the startup message with the handler number, port, address and other information
func (app *App) startupMessage(addr string, tls bool, pids string, cfg ListenConfig) {
func (app *App) startupMessage(addr string, enableTLS bool, pids string, cfg ListenConfig) { //nolint:revive TODO: Check CertKeyFile instead of control-flag.
// ignore child processes
if IsChild() {
return
@ -297,7 +302,7 @@ func (app *App) startupMessage(addr string, tls bool, pids string, cfg ListenCon
}
scheme := schemeHTTP
if tls {
if enableTLS {
scheme = schemeHTTPS
}
@ -424,7 +429,7 @@ func (app *App) printRoutesMessage() {
func (app *App) gracefulShutdown(ctx context.Context, cfg ListenConfig) {
<-ctx.Done()
if err := app.Shutdown(); err != nil {
if err := app.Shutdown(); err != nil { //nolint:contextcheck // TODO: Implement it
cfg.OnShutdownError(err)
}

View File

@ -1,3 +1,4 @@
//nolint:wrapcheck // We must not wrap errors in tests
package fiber
import (

View File

@ -45,7 +45,7 @@ func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler {
}
}
})
_ = HTTPHandler(mw(nextHandler))(c)
_ = HTTPHandler(mw(nextHandler))(c) //nolint:errcheck // TODO
if next {
return c.Next()
}
@ -81,7 +81,7 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc {
return
}
req.Header.SetContentLength(len(body))
_, _ = req.BodyWriter().Write(body)
_, _ = req.BodyWriter().Write(body) //nolint:errcheck // TODO
}
req.Header.SetMethod(r.Method)
req.SetRequestURI(r.RequestURI)
@ -121,6 +121,6 @@ func handlerFunc(app *fiber.App, h ...fiber.Handler) http.HandlerFunc {
w.Header().Add(string(k), string(v))
})
w.WriteHeader(fctx.Response.StatusCode())
_, _ = w.Write(fctx.Response.Body())
_, _ = w.Write(fctx.Response.Body()) //nolint:errcheck // not needed
}
}

View File

@ -5,6 +5,7 @@
package adaptor
import (
"context"
"fmt"
"io"
"net"
@ -71,10 +72,13 @@ func Test_HTTPHandler(t *testing.T) {
t.Fatalf("unexpected remoteAddr %q. Expecting %q", r.RemoteAddr, expectedRemoteAddr)
}
body, err := io.ReadAll(r.Body)
r.Body.Close()
if err != nil {
t.Fatalf("unexpected error when reading request body: %s", err)
}
err = r.Body.Close()
if err != nil {
t.Fatalf("unexpected error when closing request body: %s", err)
}
if string(body) != expectedBody {
t.Fatalf("unexpected body %q. Expecting %q", body, expectedBody)
}
@ -107,7 +111,10 @@ func Test_HTTPHandler(t *testing.T) {
req.Header.SetMethod(expectedMethod)
req.SetRequestURI(expectedRequestURI)
req.Header.SetHost(expectedHost)
req.BodyWriter().Write([]byte(expectedBody)) // nolint:errcheck
_, err = req.BodyWriter().Write([]byte(expectedBody))
if err != nil {
t.Fatalf("unexpected error when writing the request body: %s", err)
}
for k, v := range expectedHeader {
req.Header.Set(k, v)
}
@ -186,7 +193,10 @@ func Test_HTTPMiddleware(t *testing.T) {
})
for _, tt := range tests {
req, _ := http.NewRequest(tt.method, tt.url, nil)
req, err := http.NewRequestWithContext(context.Background(), tt.method, tt.url, nil)
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
}
resp, err := app.Test(req)
if err != nil {
t.Fatalf(`%s: %s`, t.Name(), err)
@ -194,6 +204,10 @@ func Test_HTTPMiddleware(t *testing.T) {
if resp.StatusCode != tt.statusCode {
t.Fatalf(`%s: StatusCode: got %v - expected %v`, t.Name(), resp.StatusCode, tt.statusCode)
}
err = resp.Body.Close()
if err != nil {
t.Fatalf("unexpected error when closing request body: %s", err)
}
}
}
@ -214,6 +228,8 @@ func Test_FiberAppDefaultPort(t *testing.T) {
}
func testFiberToHandlerFunc(t *testing.T, checkDefaultPort bool, app ...*fiber.App) { //revive:disable-line:flag-parameter
t.Helper()
expectedMethod := fiber.MethodPost
expectedRequestURI := "/foo/bar?baz=123"
expectedBody := "body 123 foo bar baz"

View File

@ -39,8 +39,8 @@ func Test_Middleware_BasicAuth(t *testing.T) {
}))
app.Get("/testauth", func(c fiber.Ctx) error {
username := c.Locals("username").(string)
password := c.Locals("password").(string)
username := c.Locals("username").(string) //nolint:errcheck, forcetypeassert // not needed
password := c.Locals("password").(string) //nolint:errcheck, forcetypeassert // not needed
return c.SendString(username + password)
})

View File

@ -38,8 +38,7 @@ func appWithConfig(t *testing.T, c *fiber.Config) *fiber.App {
isEarly := earlydata.IsEarly(c)
switch h := c.Get(headerName); h {
case "",
headerValOff:
case "", headerValOff:
if isEarly {
return errors.New("is early-data even though it's not")
}
@ -69,7 +68,11 @@ func appWithConfig(t *testing.T, c *fiber.Config) *fiber.App {
fiber.MethodGet,
fiber.MethodPost,
}, "/", func(c fiber.Ctx) error {
if !c.Locals(localsKeyTestValid).(bool) {
valid, ok := c.Locals(localsKeyTestValid).(bool)
if !ok {
panic(fmt.Errorf("failed to type-assert to bool"))
}
if !valid {
return errors.New("handler called even though validation failed")
}

View File

@ -1,6 +1,8 @@
package encryptcookie
import "github.com/gofiber/fiber/v3"
import (
"github.com/gofiber/fiber/v3"
)
// Config defines the config for middleware.
type Config struct {

View File

@ -1,6 +1,8 @@
package expvar
import "github.com/gofiber/fiber/v3"
import (
"github.com/gofiber/fiber/v3"
)
// Config defines the config for middleware.
type Config struct {

View File

@ -1,4 +1,3 @@
//nolint:bodyclose // Much easier to just ignore memory leaks in tests
package favicon
import (

View File

@ -21,7 +21,10 @@ func getFileExtension(p string) string {
}
func dirList(c fiber.Ctx, f fs.File) error {
ff := f.(fs.ReadDirFile)
ff, ok := f.(fs.ReadDirFile)
if !ok {
return fmt.Errorf("failed to type-assert to fs.ReadDirFile")
}
fileinfos, err := ff.ReadDir(-1)
if err != nil {
return fmt.Errorf("failed to read dir: %w", err)
@ -33,7 +36,7 @@ func dirList(c fiber.Ctx, f fs.File) error {
name := fi.Name()
info, err := fi.Info()
if err != nil {
return err
return fmt.Errorf("failed to get file info: %w", err)
}
fm[name] = info
@ -73,5 +76,10 @@ func dirList(c fiber.Ctx, f fs.File) error {
func openFile(filesystem fs.FS, name string) (fs.File, error) {
name = filepath.ToSlash(name)
return filesystem.Open(name)
file, err := filesystem.Open(name)
if err != nil {
return nil, fmt.Errorf("failed to open file: %w", err)
}
return file, nil
}

View File

@ -9,9 +9,7 @@ import (
"github.com/gofiber/fiber/v3/internal/storage/memory"
)
var (
ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
)
var ErrInvalidIdempotencyKey = errors.New("invalid idempotency key")
// Config defines the config for middleware.
type Config struct {

View File

@ -11,10 +11,8 @@ import (
"github.com/gofiber/fiber/v3"
)
var (
// When there is no request of the key thrown ErrMissingOrMalformedAPIKey
ErrMissingOrMalformedAPIKey = errors.New("missing or malformed API Key")
)
// When there is no request of the key thrown ErrMissingOrMalformedAPIKey
var ErrMissingOrMalformedAPIKey = errors.New("missing or malformed API Key")
type Config struct {
// Filter defines a function to skip middleware.

View File

@ -123,10 +123,6 @@ func New(config ...Config) fiber.Handler {
}
// Logger instance & update some logger data fields
if err = cfg.LoggerFunc(c, data, cfg); err != nil {
return err
}
return nil
return cfg.LoggerFunc(c, data, cfg)
}
}

View File

@ -1,6 +1,8 @@
package pprof
import "github.com/gofiber/fiber/v3"
import (
"github.com/gofiber/fiber/v3"
)
// Config defines the config for middleware.
type Config struct {

View File

@ -1,8 +1,8 @@
//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
//nolint:bodyclose // Much easier to just ignore memory leaks in tests
package redirect
import (

View File

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

View File

@ -1,6 +1,8 @@
package skip
import "github.com/gofiber/fiber/v3"
import (
"github.com/gofiber/fiber/v3"
)
// New creates a middleware handler which skips the wrapped handler
// if the exclude predicate returns true.

View File

@ -5,6 +5,7 @@
package fiber
import (
"fmt"
"strings"
"sync"
@ -13,17 +14,15 @@ import (
"github.com/valyala/bytebufferpool"
)
var (
// Pool for redirection
redirectPool = sync.Pool{
New: func() any {
return &Redirect{
status: StatusFound,
oldInput: make(map[string]string, 0),
}
},
}
)
// Pool for redirection
var redirectPool = sync.Pool{
New: func() any {
return &Redirect{
status: StatusFound,
oldInput: make(map[string]string, 0),
}
},
}
// Cookie name to send flash messages when to use redirection.
const (
@ -52,7 +51,12 @@ type RedirectConfig struct {
// AcquireRedirect return default Redirect reference from the redirect pool
func AcquireRedirect() *Redirect {
return redirectPool.Get().(*Redirect)
redirect, ok := redirectPool.Get().(*Redirect)
if !ok {
panic(fmt.Errorf("failed to type-assert to *Redirect"))
}
return redirect
}
// ReleaseRedirect returns c acquired via Redirect to redirect pool.
@ -103,11 +107,11 @@ func (r *Redirect) WithInput() *Redirect {
switch ctype {
case MIMEApplicationForm:
_ = r.c.Bind().Form(r.oldInput)
_ = r.c.Bind().Form(r.oldInput) //nolint:errcheck // not needed
case MIMEMultipartForm:
_ = r.c.Bind().MultipartForm(r.oldInput)
_ = r.c.Bind().MultipartForm(r.oldInput) //nolint:errcheck // not needed
default:
_ = r.c.Bind().Query(r.oldInput)
_ = r.c.Bind().Query(r.oldInput) //nolint:errcheck // not needed
}
return r
@ -286,7 +290,7 @@ func (r *Redirect) setFlash() {
r.c.ClearCookie(FlashCookieName)
}
func parseMessage(raw string) (string, string) {
func parseMessage(raw string) (key string, value string) {
if i := findNextNonEscapedCharsetPosition(raw, []byte(CookieDataAssigner)); i != -1 {
return RemoveEscapeChar(raw[:i]), RemoveEscapeChar(raw[i+1:])
}

View File

@ -2,6 +2,7 @@
// 📝 Github Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
//nolint:wrapcheck // We must not wrap errors in tests
package fiber
import (
@ -341,7 +342,7 @@ func Benchmark_Redirect_Route(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Redirect().Route("user", RedirectConfig{
c.Redirect().Route("user", RedirectConfig{ //nolint:errcheck,gosec,revive // we don't need to handle error here
Params: Map{
"name": "fiber",
},
@ -365,7 +366,7 @@ func Benchmark_Redirect_Route_WithQueries(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Redirect().Route("user", RedirectConfig{
c.Redirect().Route("user", RedirectConfig{ //nolint:errcheck,gosec,revive // we don't need to handle error here
Params: Map{
"name": "fiber",
},
@ -394,7 +395,7 @@ func Benchmark_Redirect_Route_WithFlashMessages(b *testing.B) {
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.Redirect().With("success", "1").With("message", "test").Route("user")
c.Redirect().With("success", "1").With("message", "test").Route("user") //nolint:errcheck,gosec,revive // we don't need to handle error here
}
require.Equal(b, 302, c.Response().StatusCode())

View File

@ -190,7 +190,7 @@ func (app *App) next(c *DefaultCtx) (bool, error) {
return false, err
}
func (app *App) handler(rctx *fasthttp.RequestCtx) {
func (app *App) requestHandler(rctx *fasthttp.RequestCtx) {
// Handler for default ctxs
var c CustomCtx
if app.newCtxFunc != nil {