Skip to content

♻️ refactor: Change c.Redirect() default status #3415

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ctx.go
Original file line number Diff line number Diff line change
Expand Up @@ -1313,7 +1313,7 @@ func (c *DefaultCtx) Range(size int) (Range, error) {

// Redirect returns the Redirect reference.
// Use Redirect().Status() to set custom redirection status code.
// If status is not specified, status defaults to 302 Found.
// If status is not specified, status defaults to 303 See Other.
// You can use Redirect().To(), Redirect().Route() and Redirect().Back() for redirection.
func (c *DefaultCtx) Redirect() *Redirect {
if c.redirect == nil {
Expand Down
2 changes: 1 addition & 1 deletion ctx_interface_gen.go

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

14 changes: 7 additions & 7 deletions docs/api/redirect.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ The redirect methods are used to redirect the context (request) to a different U
Redirects to the URL derived from the specified path, with a specified [status](#status), a positive integer that corresponds to an HTTP status code.

:::info
If **not** specified, status defaults to **302 Found**.
If **not** specified, status defaults to **303 See Other**.
:::

```go title="Signature"
Expand All @@ -24,7 +24,7 @@ func (r *Redirect) To(location string) error

```go title="Example"
app.Get("/coffee", func(c fiber.Ctx) error {
// => HTTP - GET 301 /teapot
// => HTTP - GET 301 /teapot
return c.Redirect().Status(fiber.StatusMovedPermanently).To("/teapot")
})

Expand All @@ -35,11 +35,11 @@ app.Get("/teapot", func(c fiber.Ctx) error {

```go title="More examples"
app.Get("/", func(c fiber.Ctx) error {
// => HTTP - GET 302 /foo/bar
// => HTTP - GET 303 /foo/bar
return c.Redirect().To("/foo/bar")
// => HTTP - GET 302 ../login
// => HTTP - GET 303 ../login
return c.Redirect().To("../login")
// => HTTP - GET 302 http://example.com
// => HTTP - GET 303 http://example.com
return c.Redirect().To("http://example.com")
// => HTTP - GET 301 https://example.com
return c.Redirect().Status(301).To("http://example.com")
Expand Down Expand Up @@ -92,7 +92,7 @@ app.Get("/user/:name", func(c fiber.Ctx) error {
Redirects back to the referer URL. It redirects to a fallback URL if the referer header doesn't exist, with a specified status, a positive integer that corresponds to an HTTP status code.

:::info
If **not** specified, status defaults to **302 Found**.
If **not** specified, status defaults to **303 See Other**.
:::

```go title="Signature"
Expand Down Expand Up @@ -134,7 +134,7 @@ func (r *Redirect) Status(status int) *Redirect

```go title="Example"
app.Get("/coffee", func(c fiber.Ctx) error {
// => HTTP - GET 301 /teapot
// => HTTP - GET 301 /teapot
return c.Redirect().Status(fiber.StatusMovedPermanently).To("/teapot")
})
```
Expand Down
2 changes: 1 addition & 1 deletion docs/extra/internal.md
Original file line number Diff line number Diff line change
Expand Up @@ -343,7 +343,7 @@ flowchart LR

### Explanation

- Redirect Struct: Retrieved from a pool (to minimize allocations), it stores redirection settings such as the HTTP status code (defaulting to 302) and any flash messages.
- Redirect Struct: Retrieved from a pool (to minimize allocations), it stores redirection settings such as the HTTP status code (defaulting to 303 See Other) and any flash messages.
- Flash Messages & Old Inputs: These are collected via methods like With() or WithInput() and then serialized and stored in a cookie named fiber_flash.
- Redirection Methods: The To(), Route(), and Back() methods determine the target URL and set the Location header accordingly.

Expand Down
11 changes: 7 additions & 4 deletions docs/whats_new.md
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,7 @@ The route method is now like [`Express`](https://expressjs.com/de/api.html#app.r

```diff
- Route(prefix string, fn func(router Router), name ...string) Router
+ Route(path string) Register
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why was this changed?

+ Route(path string) Register
```

<details>
Expand Down Expand Up @@ -299,7 +299,7 @@ Registering a subapp is now also possible via the [`Use`](./api/app#use) method
// register mulitple prefixes
app.Use(["/v1", "/v2"], func(c fiber.Ctx) error {
// Middleware for /v1 and /v2
return c.Next()
return c.Next()
})

// define subapp
Expand Down Expand Up @@ -577,6 +577,9 @@ In this example, the `Bind` method is used to bind the request body to the `User

Fiber v3 enhances the redirect functionality by introducing new methods and improving existing ones. The new redirect methods provide more flexibility and control over the redirection process.

The default response status is changes from 302 Found to 303 See Other for more
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This statement needs work. It should be a separate section.

predictable behavior across browsers.

### New Methods

- `Redirect().To()`: Redirects to a specific URL.
Expand Down Expand Up @@ -826,7 +829,7 @@ The adaptor middleware has been significantly optimized for performance and effi

### Cache

We are excited to introduce a new option in our caching middleware: Cache Invalidator. This feature provides greater control over cache management, allowing you to define a custom conditions for invalidating cache entries.
We are excited to introduce a new option in our caching middleware: Cache Invalidator. This feature provides greater control over cache management, allowing you to define a custom conditions for invalidating cache entries.
Additionally, the caching middleware has been optimized to avoid caching non-cacheable status codes, as defined by the [HTTP standards](https://datatracker.ietf.org/doc/html/rfc7231#section-6.1). This improvement enhances cache accuracy and reduces unnecessary cache storage usage.

### CORS
Expand Down Expand Up @@ -947,7 +950,7 @@ Logger provides predefined formats that you can use by name or directly by speci

```go
app.Use(logger.New(logger.Config{
Format: logger.FormatCombined,
Format: logger.FormatCombined,
}))
```

Expand Down
4 changes: 2 additions & 2 deletions middleware/expvar/expvar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ func Test_Expvar_Other_Path(t *testing.T) {
return c.SendString("escaped")
})

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars/302", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/vars/303", nil))
require.NoError(t, err)
require.Equal(t, 302, resp.StatusCode)
require.Equal(t, 303, resp.StatusCode)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use fiber.StatusSeeOther

}

// go test -run Test_Expvar_Next
Expand Down
8 changes: 4 additions & 4 deletions middleware/pprof/pprof_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,9 +153,9 @@ func Test_Pprof_Other(t *testing.T) {
return c.SendString("escaped")
})

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/302", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/debug/pprof/303", nil))
require.NoError(t, err)
require.Equal(t, 302, resp.StatusCode)
require.Equal(t, fiber.StatusSeeOther, resp.StatusCode)
}

func Test_Pprof_Other_WithPrefix(t *testing.T) {
Expand All @@ -167,9 +167,9 @@ func Test_Pprof_Other_WithPrefix(t *testing.T) {
return c.SendString("escaped")
})

resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/302", nil))
resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/federated-fiber/debug/pprof/303", nil))
require.NoError(t, err)
require.Equal(t, 302, resp.StatusCode)
require.Equal(t, fiber.StatusSeeOther, resp.StatusCode)
}

// go test -run Test_Pprof_Next
Expand Down
2 changes: 1 addition & 1 deletion middleware/redirect/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ type Config struct {

// The status code when redirecting
// This is ignored if Redirect is disabled
// Optional. Default: 302 Temporary Redirect
// Optional. Default: 303 See Other
StatusCode int
}

Expand Down
8 changes: 4 additions & 4 deletions redirect.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
var redirectPool = sync.Pool{
New: func() any {
return &Redirect{
status: StatusFound,
status: StatusSeeOther,
messages: make(redirectionMsgs, 0),
}
},
Expand Down Expand Up @@ -61,7 +61,7 @@ type FlashMessage struct {
type Redirect struct {
c *DefaultCtx // Embed ctx
messages redirectionMsgs // Flash messages and old input data
status int // Status code of redirection. Default: StatusFound
status int // Status code of redirection. Default: 303 StatusSeeOther
}

// RedirectConfig A config to use with Redirect().Route()
Expand Down Expand Up @@ -92,13 +92,13 @@ func ReleaseRedirect(r *Redirect) {
}

func (r *Redirect) release() {
r.status = 302
r.status = StatusSeeOther
r.messages = r.messages[:0]
r.c = nil
}

// Status sets the status code of redirection.
// If status is not specified, status defaults to 302 Found.
// If status is not specified, status defaults to 303 See Other.
func (r *Redirect) Status(code int) *Redirect {
r.status = code

Expand Down
35 changes: 18 additions & 17 deletions redirect_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ func Test_Redirect_To(t *testing.T) {
t.Parallel()
app := New()
c := app.AcquireCtx(&fasthttp.RequestCtx{})
defer app.ReleaseCtx(c)

err := c.Redirect().To("http://default.com")
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use fiber.StatusSeeOther

require.Equal(t, "http://default.com", string(c.Response().Header.Peek(HeaderLocation)))

err = c.Redirect().Status(301).To("http://example.com")
Expand All @@ -39,7 +40,7 @@ func Test_Redirect_To_WithFlashMessages(t *testing.T) {

err := c.Redirect().With("success", "2").With("success", "1").With("message", "test", 2).To("http://example.com")
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use fiber.StatusSeeOther

require.Equal(t, "http://example.com", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down Expand Up @@ -68,7 +69,7 @@ func Test_Redirect_Route_WithParams(t *testing.T) {
},
})
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use fiber.StatusSeeOther

require.Equal(t, "/user/fiber", string(c.Response().Header.Peek(HeaderLocation)))
}

Expand All @@ -88,7 +89,7 @@ func Test_Redirect_Route_WithParams_WithQueries(t *testing.T) {
Queries: map[string]string{"data[0][name]": "john", "data[0][age]": "10", "test": "doe"},
})
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())

// analysis of query parameters with url parsing, since a map pass is always randomly ordered
location, err := url.Parse(string(c.Response().Header.Peek(HeaderLocation)))
Expand All @@ -112,7 +113,7 @@ func Test_Redirect_Route_WithOptionalParams(t *testing.T) {
},
})
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user/fiber", string(c.Response().Header.Peek(HeaderLocation)))
}

Expand All @@ -127,7 +128,7 @@ func Test_Redirect_Route_WithOptionalParamsWithoutValue(t *testing.T) {

err := c.Redirect().Route("user")
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user/", string(c.Response().Header.Peek(HeaderLocation)))
}

Expand All @@ -146,7 +147,7 @@ func Test_Redirect_Route_WithGreedyParameters(t *testing.T) {
},
})
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user/test/routes", string(c.Response().Header.Peek(HeaderLocation)))
}

Expand All @@ -161,7 +162,7 @@ func Test_Redirect_Back(t *testing.T) {

err := c.Redirect().Back("/")
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/", string(c.Response().Header.Peek(HeaderLocation)))

err = c.Redirect().Back()
Expand All @@ -182,7 +183,7 @@ func Test_Redirect_Back_WithFlashMessages(t *testing.T) {

err := c.Redirect().With("success", "1").With("message", "test").Back("/")
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down Expand Up @@ -211,7 +212,7 @@ func Test_Redirect_Back_WithReferer(t *testing.T) {
c.Request().Header.Set(HeaderReferer, "/back")
err := c.Redirect().Back("/")
require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/back", c.Get(HeaderReferer))
require.Equal(t, "/back", string(c.Response().Header.Peek(HeaderLocation)))
}
Expand All @@ -233,7 +234,7 @@ func Test_Redirect_Route_WithFlashMessages(t *testing.T) {
require.Contains(t, c.redirect.messages, redirectionMsg{key: "message", value: "test", level: 0, isOldInput: false})

require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down Expand Up @@ -270,7 +271,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) {
require.Contains(t, c.redirect.messages, redirectionMsg{key: "name", value: "tom", isOldInput: true})

require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down Expand Up @@ -306,7 +307,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) {
require.Contains(t, c.redirect.messages, redirectionMsg{key: "name", value: "tom", isOldInput: true})

require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down Expand Up @@ -350,7 +351,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) {
require.Contains(t, c.redirect.messages, redirectionMsg{key: "name", value: "tom", isOldInput: true})

require.NoError(t, err)
require.Equal(t, 302, c.Response().StatusCode())
require.Equal(t, 303, c.Response().StatusCode())
require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down Expand Up @@ -480,7 +481,7 @@ func Benchmark_Redirect_Route(b *testing.B) {
}

require.NoError(b, err)
require.Equal(b, 302, c.Response().StatusCode())
require.Equal(b, 303, c.Response().StatusCode())
require.Equal(b, "/user/fiber", string(c.Response().Header.Peek(HeaderLocation)))
}

Expand Down Expand Up @@ -508,7 +509,7 @@ func Benchmark_Redirect_Route_WithQueries(b *testing.B) {
}

require.NoError(b, err)
require.Equal(b, 302, c.Response().StatusCode())
require.Equal(b, 303, c.Response().StatusCode())
// analysis of query parameters with url parsing, since a map pass is always randomly ordered
location, err := url.Parse(string(c.Response().Header.Peek(HeaderLocation)))
require.NoError(b, err, "url.Parse(location)")
Expand All @@ -535,7 +536,7 @@ func Benchmark_Redirect_Route_WithFlashMessages(b *testing.B) {
}

require.NoError(b, err)
require.Equal(b, 302, c.Response().StatusCode())
require.Equal(b, 303, c.Response().StatusCode())
require.Equal(b, "/user", string(c.Response().Header.Peek(HeaderLocation)))

c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing
Expand Down
Loading