Skip to content

Commit

Permalink
Merge branch 'main' into renanbastos93improve-error-handling-csrf-middle
Browse files Browse the repository at this point in the history
  • Loading branch information
gaby authored Oct 5, 2024
2 parents 7075406 + 85a5fb8 commit f5933a6
Show file tree
Hide file tree
Showing 18 changed files with 305 additions and 86 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/linter.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@ jobs:
uses: golangci/golangci-lint-action@v6
with:
# NOTE: Keep this in sync with the version from .golangci.yml
version: v1.60.3
version: v1.61.0
2 changes: 1 addition & 1 deletion .github/workflows/markdown.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
uses: actions/checkout@v4

- name: Run markdownlint-cli2
uses: DavidAnson/markdownlint-cli2-action@v16
uses: DavidAnson/markdownlint-cli2-action@v17
with:
globs: |
**/*.md
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ markdown:
## lint: 🚨 Run lint checks
.PHONY: lint
lint:
go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.60.3 run ./...
go run github.com/golangci/golangci-lint/cmd/golangci-lint@v1.61.0 run ./...

## test: 🚦 Execute all tests
.PHONY: test
Expand Down
25 changes: 20 additions & 5 deletions binder/mapping.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package binder

import (
"errors"
"reflect"
"strings"
"sync"

"github.com/gofiber/fiber/v3/internal/schema"
"github.com/gofiber/utils/v2"
"github.com/valyala/bytebufferpool"

"github.com/gofiber/fiber/v3/internal/schema"
)

// ParserConfig form decoder config for SetParserDecoder
Expand Down Expand Up @@ -132,15 +134,24 @@ func parseParamSquareBrackets(k string) (string, error) {
defer bytebufferpool.Put(bb)

kbytes := []byte(k)
openBracketsCount := 0

for i, b := range kbytes {
if b == '[' && kbytes[i+1] != ']' {
if err := bb.WriteByte('.'); err != nil {
return "", err //nolint:wrapcheck // unnecessary to wrap it
if b == '[' {
openBracketsCount++
if i+1 < len(kbytes) && kbytes[i+1] != ']' {
if err := bb.WriteByte('.'); err != nil {
return "", err //nolint:wrapcheck // unnecessary to wrap it
}
}
continue
}

if b == '[' || b == ']' {
if b == ']' {
openBracketsCount--
if openBracketsCount < 0 {
return "", errors.New("unmatched brackets")
}
continue
}

Expand All @@ -149,6 +160,10 @@ func parseParamSquareBrackets(k string) (string, error) {
}
}

if openBracketsCount > 0 {
return "", errors.New("unmatched brackets")
}

return bb.String(), nil
}

Expand Down
68 changes: 68 additions & 0 deletions binder/mapping_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package binder

import (
"errors"
"reflect"
"testing"

Expand Down Expand Up @@ -29,3 +30,70 @@ func Test_EqualFieldType(t *testing.T) {
require.True(t, equalFieldType(&user, reflect.Int, "AGE"))
require.True(t, equalFieldType(&user, reflect.Int, "age"))
}

func Test_ParseParamSquareBrackets(t *testing.T) {
tests := []struct {
err error
input string
expected string
}{
{
err: nil,
input: "foo[bar]",
expected: "foo.bar",
},
{
err: nil,
input: "foo[bar][baz]",
expected: "foo.bar.baz",
},
{
err: errors.New("unmatched brackets"),
input: "foo[bar",
expected: "",
},
{
err: errors.New("unmatched brackets"),
input: "foo[bar][baz",
expected: "",
},
{
err: errors.New("unmatched brackets"),
input: "foo]bar[",
expected: "",
},
{
err: nil,
input: "foo[bar[baz]]",
expected: "foo.bar.baz",
},
{
err: nil,
input: "",
expected: "",
},
{
err: nil,
input: "[]",
expected: "",
},
{
err: nil,
input: "foo[]",
expected: "foo",
},
}

for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
result, err := parseParamSquareBrackets(tt.input)
if tt.err != nil {
require.Error(t, err)
require.EqualError(t, err, tt.err.Error())
} else {
require.NoError(t, err)
require.Equal(t, tt.expected, result)
}
})
}
}
16 changes: 2 additions & 14 deletions ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ func (c *DefaultCtx) Fresh() bool {
if err != nil {
return false
}
return lastModifiedTime.Before(modifiedSinceTime)
return lastModifiedTime.Compare(modifiedSinceTime) != 1
}
}
}
Expand Down Expand Up @@ -1841,21 +1841,9 @@ func (c *DefaultCtx) IsProxyTrusted() bool {
return false
}

var localHosts = [...]string{"127.0.0.1", "::1"}

// IsLocalHost will return true if address is a localhost address.
func (*DefaultCtx) isLocalHost(address string) bool {
for _, h := range localHosts {
if address == h {
return true
}
}
return false
}

// IsFromLocal will return true if request came from local.
func (c *DefaultCtx) IsFromLocal() bool {
return c.isLocalHost(c.fasthttp.RemoteIP().String())
return c.fasthttp.RemoteIP().IsLoopback()
}

// Bind You can bind body, cookie, headers etc. into the map, map slice, struct easily by using Binding method.
Expand Down
2 changes: 0 additions & 2 deletions ctx_interface_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

74 changes: 74 additions & 0 deletions ctx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1397,6 +1397,10 @@ func Test_Ctx_Fresh(t *testing.T) {
require.False(t, c.Fresh())

c.Request().Header.Set(HeaderIfModifiedSince, "Wed, 21 Oct 2015 07:28:00 GMT")
require.True(t, c.Fresh())

c.Request().Header.Set(HeaderIfModifiedSince, "Wed, 21 Oct 2015 07:27:59 GMT")
c.Response().Header.Set(HeaderLastModified, "Wed, 21 Oct 2015 07:28:00 GMT")
require.False(t, c.Fresh())
}

Expand All @@ -1412,6 +1416,18 @@ func Benchmark_Ctx_Fresh_WithNoCache(b *testing.B) {
}
}

// go test -v -run=^$ -bench=Benchmark_Ctx_Fresh_LastModified -benchmem -count=4
func Benchmark_Ctx_Fresh_LastModified(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})

c.Response().Header.Set(HeaderLastModified, "Wed, 21 Oct 2015 07:28:00 GMT")
c.Request().Header.Set(HeaderIfModifiedSince, "Wed, 21 Oct 2015 07:28:00 GMT")
for n := 0; n < b.N; n++ {
c.Fresh()
}
}

// go test -run Test_Ctx_Binders -v
func Test_Ctx_Binders(t *testing.T) {
t.Parallel()
Expand Down Expand Up @@ -6352,3 +6368,61 @@ func Benchmark_Ctx_IsProxyTrusted(b *testing.B) {
})
})
}

func Benchmark_Ctx_IsFromLocalhost(b *testing.B) {
// Scenario without localhost check
b.Run("Non_Localhost", func(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://google.com:8080/test")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})

// Scenario without localhost check in parallel
b.Run("Non_Localhost_Parallel", func(b *testing.B) {
app := New()
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://google.com:8080/test")
for pb.Next() {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})
})

// Scenario with localhost check
b.Run("Localhost", func(b *testing.B) {
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://localhost:8080/test")
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})

// Scenario with localhost check in parallel
b.Run("Localhost_Parallel", func(b *testing.B) {
app := New()
b.ReportAllocs()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
c := app.AcquireCtx(&fasthttp.RequestCtx{})
c.Request().SetRequestURI("http://localhost:8080/test")
for pb.Next() {
c.IsFromLocal()
}
app.ReleaseCtx(c)
})
})
}
2 changes: 1 addition & 1 deletion docs/api/ctx.md
Original file line number Diff line number Diff line change
Expand Up @@ -788,7 +788,7 @@ Improper use of the X-Forwarded-For header can be a security risk. For details,

## Is

Returns the matching **content type**, if the incoming request’s [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header field matches the [MIME type](https://developer.mozilla.org/ru/docs/Web/HTTP/Basics_of_HTTP/MIME_types) specified by the type parameter.
Returns the matching **content type**, if the incoming request’s [Content-Type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) HTTP header field matches the [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types) specified by the type parameter.

:::info
If the request has **no** body, it returns **false**.
Expand Down
4 changes: 2 additions & 2 deletions docs/client/hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
id: hooks
title: 🎣 Hooks
description: >-
Hooks are used to manipulate request/response proccess of Fiber client.
Hooks are used to manipulate request/response process of Fiber client.
sidebar_position: 4
---

Expand Down Expand Up @@ -77,7 +77,7 @@ There are also some builtin request hooks provide some functionalities for Fiber

- [parserRequestURL](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L62): parserRequestURL customizes the URL according to the path params and query params. It's necessary for `PathParam` and `QueryParam` methods.

- [parserRequestHeader](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L113): parserRequestHeader sets request headers, cookies, body type, referer, user agent according to client and request proeprties. It's necessary to make request header and cookiejar methods functional.
- [parserRequestHeader](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L113): parserRequestHeader sets request headers, cookies, body type, referer, user agent according to client and request properties. It's necessary to make request header and cookiejar methods functional.

- [parserRequestBody](https://github.com/gofiber/fiber/blob/main/client/hooks.go#L178): parserRequestBody serializes the body automatically. It is useful for XML, JSON, form, file bodies.

Expand Down
2 changes: 1 addition & 1 deletion docs/middleware/logger.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ app.Use(logger.New(logger.Config{
app.Use(requestid.New())
app.Use(logger.New(logger.Config{
// For more options, see the Config section
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
}))

// Changing TimeZone & TimeFormat
Expand Down
4 changes: 2 additions & 2 deletions docs/middleware/recover.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/recover"
recoverer "github.com/gofiber/fiber/v3/middleware/recover"
)
```

After you initiate your Fiber app, you can use the following possibilities:

```go
// Initialize default config
app.Use(recover.New())
app.Use(recoverer.New())

// This panic will be caught by the middleware
app.Get("/", func(c fiber.Ctx) error {
Expand Down
12 changes: 6 additions & 6 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ require (
github.com/mattn/go-colorable v0.1.13
github.com/mattn/go-isatty v0.0.20
github.com/stretchr/testify v1.9.0
github.com/tinylib/msgp v1.1.8
github.com/tinylib/msgp v1.2.1
github.com/valyala/bytebufferpool v1.0.0
github.com/valyala/fasthttp v1.55.0
github.com/valyala/fasthttp v1.56.0
)

require (
github.com/andybalholm/brotli v1.1.0 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/philhofer/fwd v1.1.2 // indirect
github.com/philhofer/fwd v1.1.3-0.20240612014219-fbbf4953d986 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/valyala/tcplisten v1.0.0 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/sys v0.21.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/net v0.29.0 // indirect
golang.org/x/sys v0.25.0 // indirect
golang.org/x/text v0.18.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
Loading

0 comments on commit f5933a6

Please sign in to comment.