Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

♻️ Tidy up the codebase #1613

Merged
merged 16 commits into from Nov 5, 2021
2 changes: 1 addition & 1 deletion app.go
Expand Up @@ -897,7 +897,7 @@ func (app *App) init() *App {
}

// ErrorHandler is the application's method in charge of finding the
// appropiate handler for the given request. It searches any mounted
// appropriate handler for the given request. It searches any mounted
// sub fibers by their prefixes and if it finds a match, it uses that
// error handler. Otherwise it uses the configured error handler for
// the app, which if not set is the DefaultErrorHandler.
Expand Down
17 changes: 8 additions & 9 deletions app_test.go
Expand Up @@ -34,6 +34,8 @@ var testEmptyHandler = func(c *Ctx) error {
}

func testStatus200(t *testing.T, app *App, url string, method string) {
t.Helper()

req := httptest.NewRequest(method, url, nil)

resp, err := app.Test(req)
Expand Down Expand Up @@ -447,7 +449,6 @@ func Test_App_Chaining(t *testing.T) {
resp, err = app.Test(req)
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 203, resp.StatusCode, "Status code")

}

func Test_App_Order(t *testing.T) {
Expand Down Expand Up @@ -478,8 +479,9 @@ func Test_App_Order(t *testing.T) {
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, "123", string(body))
}

func Test_App_Methods(t *testing.T) {
var dummyHandler = testEmptyHandler
dummyHandler := testEmptyHandler

app := New()

Expand Down Expand Up @@ -515,7 +517,6 @@ func Test_App_Methods(t *testing.T) {

app.Use("/:john?/:doe?", dummyHandler)
testStatus200(t, app, "/john/doe", MethodGet)

}

func Test_App_New(t *testing.T) {
Expand Down Expand Up @@ -652,7 +653,6 @@ func Test_App_Static_Group(t *testing.T) {
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
utils.AssertEqual(t, false, resp.Header.Get(HeaderContentLength) == "")
utils.AssertEqual(t, MIMETextHTMLCharsetUTF8, resp.Header.Get(HeaderContentType))

}

func Test_App_Static_Wildcard(t *testing.T) {
Expand All @@ -670,7 +670,6 @@ func Test_App_Static_Wildcard(t *testing.T) {
body, err := ioutil.ReadAll(resp.Body)
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, true, strings.Contains(string(body), "Test file"))

}

func Test_App_Static_Prefix_Wildcard(t *testing.T) {
Expand Down Expand Up @@ -887,7 +886,7 @@ func Test_App_Group_Mount(t *testing.T) {
}

func Test_App_Group(t *testing.T) {
var dummyHandler = testEmptyHandler
dummyHandler := testEmptyHandler

app := New()

Expand Down Expand Up @@ -937,18 +936,18 @@ func Test_App_Group(t *testing.T) {
resp, err := app.Test(httptest.NewRequest(MethodPost, "/test/v1/", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
//utils.AssertEqual(t, "/test/v1", resp.Header.Get("Location"), "Location")
// utils.AssertEqual(t, "/test/v1", resp.Header.Get("Location"), "Location")

api.Get("/users", dummyHandler)
resp, err = app.Test(httptest.NewRequest(MethodGet, "/test/v1/UsErS", nil))
utils.AssertEqual(t, nil, err, "app.Test(req)")
utils.AssertEqual(t, 200, resp.StatusCode, "Status code")
//utils.AssertEqual(t, "/test/v1/users", resp.Header.Get("Location"), "Location")
// utils.AssertEqual(t, "/test/v1/users", resp.Header.Get("Location"), "Location")
}

func Test_App_Deep_Group(t *testing.T) {
runThroughCount := 0
var dummyHandler = func(c *Ctx) error {
dummyHandler := func(c *Ctx) error {
runThroughCount++
return c.Next()
}
Expand Down
10 changes: 7 additions & 3 deletions client_test.go
Expand Up @@ -307,7 +307,6 @@ func Test_Client_Agent_Set_Or_Add_Headers(t *testing.T) {
AddBytesKV([]byte("k1"), []byte("v33")).
SetBytesKV([]byte("k2"), []byte("v2")).
Add("k2", "v22")

}

testAgent(t, handler, wrapAgent, "K1v1K1v11K1v22K1v33K2v2K2v22")
Expand Down Expand Up @@ -700,7 +699,7 @@ func Test_Client_Agent_MultipartForm_SendFiles(t *testing.T) {
fh1, err := c.FormFile("field1")
utils.AssertEqual(t, nil, err)
utils.AssertEqual(t, fh1.Filename, "name")
buf := make([]byte, fh1.Size, fh1.Size)
buf := make([]byte, fh1.Size)
f, err := fh1.Open()
utils.AssertEqual(t, nil, err)
defer func() { _ = f.Close() }()
Expand Down Expand Up @@ -746,13 +745,15 @@ func Test_Client_Agent_MultipartForm_SendFiles(t *testing.T) {
}

func checkFormFile(t *testing.T, fh *multipart.FileHeader, filename string) {
t.Helper()

basename := filepath.Base(filename)
utils.AssertEqual(t, fh.Filename, basename)

b1, err := ioutil.ReadFile(filename)
utils.AssertEqual(t, nil, err)

b2 := make([]byte, fh.Size, fh.Size)
b2 := make([]byte, fh.Size)
f, err := fh.Open()
utils.AssertEqual(t, nil, err)
defer func() { _ = f.Close() }()
Expand Down Expand Up @@ -998,6 +999,8 @@ func Test_Client_Agent_Struct(t *testing.T) {
go func() { utils.AssertEqual(t, nil, app.Listener(ln)) }()

t.Run("success", func(t *testing.T) {
t.Parallel()

a := Get("http://example.com")

a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() }
Expand All @@ -1013,6 +1016,7 @@ func Test_Client_Agent_Struct(t *testing.T) {
})

t.Run("pre error", func(t *testing.T) {
t.Parallel()
a := Get("http://example.com")

a.HostClient.Dial = func(addr string) (net.Conn, error) { return ln.Dial() }
Expand Down
24 changes: 12 additions & 12 deletions ctx.go
Expand Up @@ -301,7 +301,7 @@ func SetParserDecoder(parserConfig ParserConfig) {
}

func decoderBuilder(parserConfig ParserConfig) interface{} {
var decoder = schema.NewDecoder()
decoder := schema.NewDecoder()
decoder.IgnoreUnknownKeys(parserConfig.IgnoreUnknownKeys)
if parserConfig.SetAliasTag != "" {
decoder.SetAliasTag(parserConfig.SetAliasTag)
Expand Down Expand Up @@ -518,8 +518,8 @@ func (c *Ctx) FormValue(key string, defaultValue ...string) string {
// https://github.com/jshttp/fresh/blob/10e0471669dbbfbfd8de65bc6efac2ddd0bfa057/index.js#L33
func (c *Ctx) Fresh() bool {
// fields
var modifiedSince = c.Get(HeaderIfModifiedSince)
var noneMatch = c.Get(HeaderIfNoneMatch)
modifiedSince := c.Get(HeaderIfModifiedSince)
noneMatch := c.Get(HeaderIfNoneMatch)

// unconditional request
if modifiedSince == "" && noneMatch == "" {
Expand All @@ -536,7 +536,7 @@ func (c *Ctx) Fresh() bool {

// if-none-match
if noneMatch != "" && noneMatch != "*" {
var etag = c.app.getString(c.fasthttp.Response.Header.Peek(HeaderETag))
etag := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderETag))
if etag == "" {
return false
}
Expand All @@ -545,7 +545,7 @@ func (c *Ctx) Fresh() bool {
}

if modifiedSince != "" {
var lastModified = c.app.getString(c.fasthttp.Response.Header.Peek(HeaderLastModified))
lastModified := c.app.getString(c.fasthttp.Response.Header.Peek(HeaderLastModified))
if lastModified != "" {
lastModifiedTime, err := http.ParseTime(lastModified)
if err != nil {
Expand Down Expand Up @@ -576,7 +576,6 @@ func (c *Ctx) Get(key string, defaultValue ...string) string {
// Make copies or use the Immutable setting instead.
func (c *Ctx) GetRespHeader(key string, defaultValue ...string) string {
return defaultString(c.app.getString(c.fasthttp.Response.Header.Peek(key)), defaultValue)

}

// Hostname contains the hostname derived from the X-Forwarded-Host or Host HTTP header.
Expand Down Expand Up @@ -662,7 +661,6 @@ func (c *Ctx) JSON(data interface{}) error {
// By default, the callback name is simply callback.
func (c *Ctx) JSONP(data interface{}, callback ...string) error {
raw, err := json.Marshal(data)

if err != nil {
return err
}
Expand Down Expand Up @@ -856,7 +854,7 @@ func (c *Ctx) Query(key string, defaultValue ...string) string {
// QueryParser binds the query string to a struct.
func (c *Ctx) QueryParser(out interface{}) error {
// Get decoder from pool
var decoder = decoderPool.Get().(*schema.Decoder)
decoder := decoderPool.Get().(*schema.Decoder)
defer decoderPool.Put(decoder)

// Set correct alias tag
Expand Down Expand Up @@ -1063,9 +1061,11 @@ func (c *Ctx) Send(body []byte) error {
return nil
}

var sendFileOnce sync.Once
var sendFileFS *fasthttp.FS
var sendFileHandler fasthttp.RequestHandler
var (
sendFileOnce sync.Once
sendFileFS *fasthttp.FS
sendFileHandler fasthttp.RequestHandler
)

// SendFile transfers the file from the given path.
// The file is not compressed by default, enable this by passing a 'true' argument
Expand Down Expand Up @@ -1094,7 +1094,7 @@ func (c *Ctx) SendFile(file string, compress ...bool) error {
// Keep original path for mutable params
c.pathOriginal = utils.CopyString(c.pathOriginal)
// Disable compression
if len(compress) <= 0 || !compress[0] {
if len(compress) == 0 || !compress[0] {
// https://github.com/valyala/fasthttp/blob/master/fs.go#L46
c.fasthttp.Request.Header.Del(HeaderAcceptEncoding)
}
Expand Down
30 changes: 12 additions & 18 deletions ctx_test.go
Expand Up @@ -22,7 +22,6 @@ import (
"reflect"
"strconv"
"strings"
"sync"
"testing"
"text/template"
"time"
Expand Down Expand Up @@ -403,7 +402,7 @@ func Test_Ctx_BodyParser(t *testing.T) {
func Test_Ctx_BodyParser_WithSetParserDecoder(t *testing.T) {
type CustomTime time.Time

var timeConverter = func(value string) reflect.Value {
timeConverter := func(value string) reflect.Value {
if v, err := time.Parse("2006-01-02", value); err == nil {
return reflect.ValueOf(v)
}
Expand Down Expand Up @@ -567,7 +566,6 @@ func Test_Ctx_UserContext(t *testing.T) {
t.Run("Nil_Context", func(t *testing.T) {
ctx := c.UserContext()
utils.AssertEqual(t, ctx, context.Background())

})
t.Run("ValueContext", func(t *testing.T) {
testKey := "Test Key"
Expand Down Expand Up @@ -634,12 +632,12 @@ func Test_Ctx_Cookie(t *testing.T) {
expire := time.Now().Add(24 * time.Hour)
var dst []byte
dst = expire.In(time.UTC).AppendFormat(dst, time.RFC1123)
httpdate := strings.Replace(string(dst), "UTC", "GMT", -1)
httpdate := strings.ReplaceAll(string(dst), "UTC", "GMT")
cookie := &Cookie{
Name: "username",
Value: "john",
Expires: expire,
//SameSite: CookieSameSiteStrictMode, // default is "lax"
// SameSite: CookieSameSiteStrictMode, // default is "lax"
}
c.Cookie(cookie)
expect := "username=john; expires=" + httpdate + "; path=/; SameSite=Lax"
Expand Down Expand Up @@ -1233,7 +1231,6 @@ func Benchmark_Ctx_MultipartForm(b *testing.B) {
for n := 0; n < b.N; n++ {
h(c)
}

}

// go test -run Test_Ctx_OriginalURL
Expand Down Expand Up @@ -1452,19 +1449,19 @@ func Test_Ctx_Range(t *testing.T) {
err error
)

result, err = c.Range(1000)
_, err = c.Range(1000)
utils.AssertEqual(t, true, err != nil)

c.Request().Header.Set(HeaderRange, "bytes=500")
result, err = c.Range(1000)
_, err = c.Range(1000)
utils.AssertEqual(t, true, err != nil)

c.Request().Header.Set(HeaderRange, "bytes=500=")
result, err = c.Range(1000)
_, err = c.Range(1000)
utils.AssertEqual(t, true, err != nil)

c.Request().Header.Set(HeaderRange, "bytes=500-300")
result, err = c.Range(1000)
_, err = c.Range(1000)
utils.AssertEqual(t, true, err != nil)

testRange := func(header string, start, end int) {
Expand Down Expand Up @@ -1827,7 +1824,7 @@ func Benchmark_Ctx_JSONP(b *testing.B) {
Name: "Grame",
Age: 20,
}
var callback = "emit"
callback := "emit"
var err error
b.ReportAllocs()
b.ResetTimer()
Expand Down Expand Up @@ -1951,7 +1948,6 @@ func Test_Ctx_Render(t *testing.T) {
}

type testTemplateEngine struct {
mu sync.Mutex
templates *template.Template
}

Expand Down Expand Up @@ -2077,7 +2073,7 @@ func Benchmark_Ctx_Send(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
var byt = []byte("Hello, World!")
byt := []byte("Hello, World!")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
Expand Down Expand Up @@ -2158,15 +2154,14 @@ func Test_Ctx_Set_Splitter(t *testing.T) {
c.Set("Location", "foo\nSet-Cookie:%20SESSIONID=MaliciousValue\n")
h = string(c.Response().Header.Peek("Location"))
utils.AssertEqual(t, false, strings.Contains(h, "\n"), h)

}

// go test -v -run=^$ -bench=Benchmark_Ctx_Set -benchmem -count=4
func Benchmark_Ctx_Set(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
var val = "1431-15132-3423"
val := "1431-15132-3423"
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
Expand Down Expand Up @@ -2272,7 +2267,7 @@ func Benchmark_Ctx_Write(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)
var byt = []byte("Hello, World!")
byt := []byte("Hello, World!")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
Expand Down Expand Up @@ -2400,7 +2395,7 @@ func Test_Ctx_QueryParser(t *testing.T) {
func Test_Ctx_QueryParser_WithSetParserDecoder(t *testing.T) {
type NonRFCTime time.Time

var NonRFCConverter = func(value string) reflect.Value {
NonRFCConverter := func(value string) reflect.Value {
if v, err := time.Parse("2006-01-02", value); err == nil {
return reflect.ValueOf(v)
}
Expand Down Expand Up @@ -2743,7 +2738,6 @@ func TestCtx_ParamsInt(t *testing.T) {
app.Test(httptest.NewRequest(MethodGet, "/testnoint/xd", nil))
app.Test(httptest.NewRequest(MethodGet, "/testignoredefault/2222", nil))
app.Test(httptest.NewRequest(MethodGet, "/testdefault/xd", nil))

}

// go test -run Test_Ctx_GetRespHeader
Expand Down
2 changes: 1 addition & 1 deletion group.go
Expand Up @@ -48,7 +48,7 @@ func (grp *Group) Mount(prefix string, fiber *App) Router {
//
// This method will match all HTTP verbs: GET, POST, PUT, HEAD etc...
func (grp *Group) Use(args ...interface{}) Router {
var prefix = ""
prefix := ""
var handlers []Handler
for i := 0; i < len(args); i++ {
switch arg := args[i].(type) {
Expand Down