diff --git a/bind.go b/bind.go index e202cd85e0..eff595cd72 100644 --- a/bind.go +++ b/bind.go @@ -95,7 +95,7 @@ func (b *Bind) RespHeader(out any) error { // Cookie binds the requesr cookie strings into the struct, map[string]string and map[string][]string. // NOTE: If your cookie is like key=val1,val2; they'll be binded as an slice if your map is map[string][]string. Else, it'll use last element of cookie. func (b *Bind) Cookie(out any) error { - if err := b.returnErr(binder.CookieBinder.Bind(b.ctx.Context(), out)); err != nil { + if err := b.returnErr(binder.CookieBinder.Bind(b.ctx.RequestCtx(), out)); err != nil { return err } @@ -104,7 +104,7 @@ func (b *Bind) Cookie(out any) error { // Query binds the query string into the struct, map[string]string and map[string][]string. func (b *Bind) Query(out any) error { - if err := b.returnErr(binder.QueryBinder.Bind(b.ctx.Context(), out)); err != nil { + if err := b.returnErr(binder.QueryBinder.Bind(b.ctx.RequestCtx(), out)); err != nil { return err } @@ -131,7 +131,7 @@ func (b *Bind) XML(out any) error { // Form binds the form into the struct, map[string]string and map[string][]string. func (b *Bind) Form(out any) error { - if err := b.returnErr(binder.FormBinder.Bind(b.ctx.Context(), out)); err != nil { + if err := b.returnErr(binder.FormBinder.Bind(b.ctx.RequestCtx(), out)); err != nil { return err } @@ -149,7 +149,7 @@ func (b *Bind) URI(out any) error { // MultipartForm binds the multipart form into the struct, map[string]string and map[string][]string. func (b *Bind) MultipartForm(out any) error { - if err := b.returnErr(binder.FormBinder.BindMultipart(b.ctx.Context(), out)); err != nil { + if err := b.returnErr(binder.FormBinder.BindMultipart(b.ctx.RequestCtx(), out)); err != nil { return err } @@ -163,7 +163,7 @@ func (b *Bind) MultipartForm(out any) error { // If there're no custom binder for mime type of body, it will return a ErrUnprocessableEntity error. func (b *Bind) Body(out any) error { // Get content-type - ctype := utils.ToLower(utils.UnsafeString(b.ctx.Context().Request.Header.ContentType())) + ctype := utils.ToLower(utils.UnsafeString(b.ctx.RequestCtx().Request.Header.ContentType())) ctype = binder.FilterFlags(utils.ParseVendorSpecificContentType(ctype)) // Check custom binders diff --git a/client/client_test.go b/client/client_test.go index b8dd39bbf0..0323f70ccd 100644 --- a/client/client_test.go +++ b/client/client_test.go @@ -1572,7 +1572,7 @@ func Test_Client_SetProxyURL(t *testing.T) { } c.Status(resp.StatusCode()) - c.Context().SetBody(resp.Body()) + c.RequestCtx().SetBody(resp.Body()) return nil }) diff --git a/ctx.go b/ctx.go index 1bbf2ba130..b68bff519d 100644 --- a/ctx.go +++ b/ctx.go @@ -382,26 +382,26 @@ func (c *DefaultCtx) ClearCookie(key ...string) { }) } -// Context returns *fasthttp.RequestCtx that carries a deadline +// RequestCtx returns *fasthttp.RequestCtx that carries a deadline // a cancellation signal, and other values across API boundaries. -func (c *DefaultCtx) Context() *fasthttp.RequestCtx { +func (c *DefaultCtx) RequestCtx() *fasthttp.RequestCtx { return c.fasthttp } -// UserContext returns a context implementation that was set by +// Context returns a context implementation that was set by // user earlier or returns a non-nil, empty context,if it was not set earlier. -func (c *DefaultCtx) UserContext() context.Context { +func (c *DefaultCtx) Context() context.Context { ctx, ok := c.fasthttp.UserValue(userContextKey).(context.Context) if !ok { ctx = context.Background() - c.SetUserContext(ctx) + c.SetContext(ctx) } return ctx } -// SetUserContext sets a context implementation by user. -func (c *DefaultCtx) SetUserContext(ctx context.Context) { +// SetContext sets a context implementation by user. +func (c *DefaultCtx) SetContext(ctx context.Context) { c.fasthttp.SetUserValue(userContextKey, ctx) } @@ -1189,8 +1189,8 @@ func (c *DefaultCtx) Query(key string, defaultValue ...string) string { // Queries()["filters[customer][name]"] == "Alice" // Queries()["filters[status]"] == "pending" func (c *DefaultCtx) Queries() map[string]string { - m := make(map[string]string, c.Context().QueryArgs().Len()) - c.Context().QueryArgs().VisitAll(func(key, value []byte) { + m := make(map[string]string, c.RequestCtx().QueryArgs().Len()) + c.RequestCtx().QueryArgs().VisitAll(func(key, value []byte) { m[c.app.getString(key)] = c.app.getString(value) }) return m @@ -1219,7 +1219,7 @@ func (c *DefaultCtx) Queries() map[string]string { // unknown := Query[string](c, "unknown", "default") // Returns "default" since the query parameter "unknown" is not found func Query[V GenericType](c Ctx, key string, defaultValue ...V) V { var v V - q := c.App().getString(c.Context().QueryArgs().Peek(key)) + q := c.App().getString(c.RequestCtx().QueryArgs().Peek(key)) return genericParseType[V](q, v, defaultValue...) } @@ -1629,7 +1629,7 @@ func (c *DefaultCtx) SendFile(file string, config ...SendFile) error { // Apply cache control header if status != StatusNotFound && status != StatusForbidden { if len(cacheControlValue) > 0 { - c.Context().Response.Header.Set(HeaderCacheControl, cacheControlValue) + c.RequestCtx().Response.Header.Set(HeaderCacheControl, cacheControlValue) } return nil diff --git a/ctx_interface_gen.go b/ctx_interface_gen.go index 0714b24329..9fd434bc3e 100644 --- a/ctx_interface_gen.go +++ b/ctx_interface_gen.go @@ -45,14 +45,14 @@ type Ctx interface { // ClearCookie expires a specific cookie by key on the client side. // If no key is provided it expires all cookies that came with the request. ClearCookie(key ...string) - // Context returns *fasthttp.RequestCtx that carries a deadline + // RequestCtx returns *fasthttp.RequestCtx that carries a deadline // a cancellation signal, and other values across API boundaries. - Context() *fasthttp.RequestCtx - // UserContext returns a context implementation that was set by + RequestCtx() *fasthttp.RequestCtx + // Context returns a context implementation that was set by // user earlier or returns a non-nil, empty context,if it was not set earlier. - UserContext() context.Context - // SetUserContext sets a context implementation by user. - SetUserContext(ctx context.Context) + Context() context.Context + // SetContext sets a context implementation by user. + SetContext(ctx context.Context) // Cookie sets a cookie by passing a cookie struct. Cookie(cookie *Cookie) // Cookies are used for getting a cookie value by key. diff --git a/ctx_test.go b/ctx_test.go index 3b6b44ebac..48360cb5f3 100644 --- a/ctx_test.go +++ b/ctx_test.go @@ -843,24 +843,24 @@ func Benchmark_Ctx_Body_With_Compression_Immutable(b *testing.B) { } } -// go test -run Test_Ctx_Context -func Test_Ctx_Context(t *testing.T) { +// go test -run Test_Ctx_RequestCtx +func Test_Ctx_RequestCtx(t *testing.T) { t.Parallel() app := New() c := app.AcquireCtx(&fasthttp.RequestCtx{}) - require.Equal(t, "*fasthttp.RequestCtx", fmt.Sprintf("%T", c.Context())) + require.Equal(t, "*fasthttp.RequestCtx", fmt.Sprintf("%T", c.RequestCtx())) } -// go test -run Test_Ctx_UserContext -func Test_Ctx_UserContext(t *testing.T) { +// go test -run Test_Ctx_Context +func Test_Ctx_Context(t *testing.T) { t.Parallel() app := New() c := app.AcquireCtx(&fasthttp.RequestCtx{}) t.Run("Nil_Context", func(t *testing.T) { t.Parallel() - ctx := c.UserContext() + ctx := c.Context() require.Equal(t, ctx, context.Background()) }) t.Run("ValueContext", func(t *testing.T) { @@ -872,8 +872,8 @@ func Test_Ctx_UserContext(t *testing.T) { }) } -// go test -run Test_Ctx_SetUserContext -func Test_Ctx_SetUserContext(t *testing.T) { +// go test -run Test_Ctx_SetContext +func Test_Ctx_SetContext(t *testing.T) { t.Parallel() app := New() c := app.AcquireCtx(&fasthttp.RequestCtx{}) @@ -881,19 +881,19 @@ func Test_Ctx_SetUserContext(t *testing.T) { testKey := struct{}{} testValue := "Test Value" ctx := context.WithValue(context.Background(), testKey, testValue) //nolint: staticcheck // not needed for tests - c.SetUserContext(ctx) - require.Equal(t, testValue, c.UserContext().Value(testKey)) + c.SetContext(ctx) + require.Equal(t, testValue, c.Context().Value(testKey)) } -// go test -run Test_Ctx_UserContext_Multiple_Requests -func Test_Ctx_UserContext_Multiple_Requests(t *testing.T) { +// go test -run Test_Ctx_Context_Multiple_Requests +func Test_Ctx_Context_Multiple_Requests(t *testing.T) { t.Parallel() testKey := struct{}{} testValue := "foobar-value" app := New() app.Get("/", func(c Ctx) error { - ctx := c.UserContext() + ctx := c.Context() if ctx.Value(testKey) != nil { return c.SendStatus(StatusInternalServerError) @@ -901,7 +901,7 @@ func Test_Ctx_UserContext_Multiple_Requests(t *testing.T) { input := utils.CopyString(Query(c, "input", "NO_VALUE")) ctx = context.WithValue(ctx, testKey, fmt.Sprintf("%s_%s", testValue, input)) //nolint: staticcheck // not needed for tests - c.SetUserContext(ctx) + c.SetContext(ctx) return c.Status(StatusOK).SendString(fmt.Sprintf("resp_%s_returned", input)) }) @@ -913,7 +913,7 @@ func Test_Ctx_UserContext_Multiple_Requests(t *testing.T) { resp, err := app.Test(httptest.NewRequest(MethodGet, fmt.Sprintf("/?input=%d", i), nil)) require.NoError(t, err, "Unexpected error from response") - require.Equal(t, StatusOK, resp.StatusCode, "context.Context returned from c.UserContext() is reused") + require.Equal(t, StatusOK, resp.StatusCode, "context.Context returned from c.Context() is reused") b, err := io.ReadAll(resp.Body) require.NoError(t, err, "Unexpected error from reading response body") @@ -3220,7 +3220,7 @@ func Test_Ctx_SendFile_MaxAge(t *testing.T) { // check expectation require.NoError(t, err) require.Equal(t, expectFileContent, c.Response().Body()) - require.Equal(t, "public, max-age=100", string(c.Context().Response.Header.Peek(HeaderCacheControl)), "CacheControl Control") + require.Equal(t, "public, max-age=100", string(c.RequestCtx().Response.Header.Peek(HeaderCacheControl)), "CacheControl Control") require.Equal(t, StatusOK, c.Response().StatusCode()) app.ReleaseCtx(c) } diff --git a/docs/api/ctx.md b/docs/api/ctx.md index 52d8144187..7ba14d053f 100644 --- a/docs/api/ctx.md +++ b/docs/api/ctx.md @@ -1891,18 +1891,18 @@ app.Get("/", func(c fiber.Ctx) error { }) ``` -## SetUserContext +## SetContext Sets the user specified implementation for context interface. ```go title="Signature" -func (c Ctx) SetUserContext(ctx context.Context) +func (c Ctx) SetContext(ctx context.Context) ``` ```go title="Example" app.Get("/", func(c fiber.Ctx) error { ctx := context.Background() - c.SetUserContext(ctx) + c.SetContext(ctx) // Here ctx could be any context implementation // ... @@ -2005,18 +2005,18 @@ app.Get("/", func(c fiber.Ctx) error { }) ``` -## UserContext +## Context -UserContext returns a context implementation that was set by user earlier +Context returns a context implementation that was set by user earlier or returns a non-nil, empty context, if it was not set earlier. ```go title="Signature" -func (c Ctx) UserContext() context.Context +func (c Ctx) Context() context.Context ``` ```go title="Example" app.Get("/", func(c fiber.Ctx) error { - ctx := c.UserContext() + ctx := c.Context() // ctx is context implementation set by user // ... diff --git a/docs/middleware/timeout.md b/docs/middleware/timeout.md index 8f94f0567f..87421d20b9 100644 --- a/docs/middleware/timeout.md +++ b/docs/middleware/timeout.md @@ -8,7 +8,7 @@ There exist two distinct implementations of timeout middleware [Fiber](https://g ## New -As a `fiber.Handler` wrapper, it creates a context with `context.WithTimeout` and pass it in `UserContext`. +As a `fiber.Handler` wrapper, it creates a context with `context.WithTimeout` which is then used with `c.Context()`. If the context passed executions (eg. DB ops, Http calls) takes longer than the given duration to return, the timeout error is set and forwarded to the centralized `ErrorHandler`. @@ -38,7 +38,7 @@ func main() { app := fiber.New() h := func(c fiber.Ctx) error { sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms") - if err := sleepWithContext(c.UserContext(), sleepTime); err != nil { + if err := sleepWithContext(c.Context(), sleepTime); err != nil { return fmt.Errorf("%w: execution error", err) } return nil @@ -84,7 +84,7 @@ func main() { app := fiber.New() h := func(c fiber.Ctx) error { sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms") - if err := sleepWithContextWithCustomError(c.UserContext(), sleepTime); err != nil { + if err := sleepWithContextWithCustomError(c.Context(), sleepTime); err != nil { return fmt.Errorf("%w: execution error", err) } return nil @@ -116,7 +116,7 @@ func main() { db, _ := gorm.Open(postgres.Open("postgres://localhost/foodb"), &gorm.Config{}) handler := func(ctx fiber.Ctx) error { - tran := db.WithContext(ctx.UserContext()).Begin() + tran := db.WithContext(ctx.Context()).Begin() if tran = tran.Exec("SELECT pg_sleep(50)"); tran.Error != nil { return tran.Error diff --git a/middleware/adaptor/adaptor.go b/middleware/adaptor/adaptor.go index 03c6287e6f..1f47ee537d 100644 --- a/middleware/adaptor/adaptor.go +++ b/middleware/adaptor/adaptor.go @@ -34,7 +34,7 @@ func HTTPHandlerFunc(h http.HandlerFunc) fiber.Handler { func HTTPHandler(h http.Handler) fiber.Handler { return func(c fiber.Ctx) error { handler := fasthttpadaptor.NewFastHTTPHandler(h) - handler(c.Context()) + handler(c.RequestCtx()) return nil } } @@ -43,7 +43,7 @@ func HTTPHandler(h http.Handler) fiber.Handler { // forServer should be set to true when the http.Request is going to be passed to a http.Handler. func ConvertRequest(c fiber.Ctx, forServer bool) (*http.Request, error) { var req http.Request - if err := fasthttpadaptor.ConvertRequest(c.Context(), &req, forServer); err != nil { + if err := fasthttpadaptor.ConvertRequest(c.RequestCtx(), &req, forServer); err != nil { return nil, err //nolint:wrapcheck // This must not be wrapped } return &req, nil @@ -108,7 +108,7 @@ func HTTPMiddleware(mw func(http.Handler) http.Handler) fiber.Handler { c.Request().Header.Set(key, v) } } - CopyContextToFiberContext(r.Context(), c.Context()) + CopyContextToFiberContext(r.Context(), c.RequestCtx()) }) if err := HTTPHandler(mw(nextHandler))(c); err != nil { diff --git a/middleware/adaptor/adaptor_test.go b/middleware/adaptor/adaptor_test.go index 990d421dec..67c306febf 100644 --- a/middleware/adaptor/adaptor_test.go +++ b/middleware/adaptor/adaptor_test.go @@ -162,7 +162,7 @@ func Test_HTTPMiddleware(t *testing.T) { app := fiber.New() app.Use(HTTPMiddleware(nethttpMW)) app.Post("/", func(c fiber.Ctx) error { - value := c.Context().Value(TestContextKey) + value := c.RequestCtx().Value(TestContextKey) val, ok := value.(string) if !ok { t.Error("unexpected error on type-assertion") @@ -170,7 +170,7 @@ func Test_HTTPMiddleware(t *testing.T) { if value != nil { c.Set("context_okay", val) } - value = c.Context().Value(TestContextSecondKey) + value = c.RequestCtx().Value(TestContextSecondKey) if value != nil { val, ok := value.(string) if !ok { @@ -316,12 +316,12 @@ func testFiberToHandlerFunc(t *testing.T, checkDefaultPort bool, app ...*fiber.A fiberH := func(c fiber.Ctx) error { callsCount++ require.Equal(t, expectedMethod, c.Method(), "Method") - require.Equal(t, expectedRequestURI, string(c.Context().RequestURI()), "RequestURI") - require.Equal(t, expectedContentLength, c.Context().Request.Header.ContentLength(), "ContentLength") + require.Equal(t, expectedRequestURI, string(c.RequestCtx().RequestURI()), "RequestURI") + require.Equal(t, expectedContentLength, c.RequestCtx().Request.Header.ContentLength(), "ContentLength") require.Equal(t, expectedHost, c.Hostname(), "Host") require.Equal(t, expectedHost, string(c.Request().Header.Host()), "Host") require.Equal(t, "http://"+expectedHost, c.BaseURL(), "BaseURL") - require.Equal(t, expectedRemoteAddr, c.Context().RemoteAddr().String(), "RemoteAddr") + require.Equal(t, expectedRemoteAddr, c.RequestCtx().RemoteAddr().String(), "RemoteAddr") body := string(c.Body()) require.Equal(t, expectedBody, body, "Body") @@ -392,8 +392,8 @@ func Test_FiberHandler_RequestNilBody(t *testing.T) { fiberH := func(c fiber.Ctx) error { callsCount++ require.Equal(t, expectedMethod, c.Method(), "Method") - require.Equal(t, expectedRequestURI, string(c.Context().RequestURI()), "RequestURI") - require.Equal(t, expectedContentLength, c.Context().Request.Header.ContentLength(), "ContentLength") + require.Equal(t, expectedRequestURI, string(c.RequestCtx().RequestURI()), "RequestURI") + require.Equal(t, expectedContentLength, c.RequestCtx().Request.Header.ContentLength(), "ContentLength") _, err := c.Write([]byte("request body is nil")) return err diff --git a/middleware/cache/cache_test.go b/middleware/cache/cache_test.go index 8f00f1f156..22ab0e2895 100644 --- a/middleware/cache/cache_test.go +++ b/middleware/cache/cache_test.go @@ -894,7 +894,7 @@ func Test_Cache_MaxBytesSizes(t *testing.T) { })) app.Get("/*", func(c fiber.Ctx) error { - path := c.Context().URI().LastPathSegment() + path := c.RequestCtx().URI().LastPathSegment() size, err := strconv.Atoi(string(path)) require.NoError(t, err) return c.Send(make([]byte, size)) diff --git a/middleware/compress/compress.go b/middleware/compress/compress.go index 00f109148e..6bd1ae09c4 100644 --- a/middleware/compress/compress.go +++ b/middleware/compress/compress.go @@ -56,7 +56,7 @@ func New(config ...Config) fiber.Handler { } // Compress response - compressor(c.Context()) + compressor(c.RequestCtx()) // Return from handler return nil diff --git a/middleware/etag/etag.go b/middleware/etag/etag.go index f28a33cec5..a00dd62bf4 100644 --- a/middleware/etag/etag.go +++ b/middleware/etag/etag.go @@ -80,7 +80,7 @@ func New(config ...Config) fiber.Handler { // Check if server's ETag is weak if bytes.Equal(clientEtag[2:], etag) || bytes.Equal(clientEtag[2:], etag[2:]) { // W/1 == 1 || W/1 == W/1 - c.Context().ResetBody() + c.RequestCtx().ResetBody() return c.SendStatus(fiber.StatusNotModified) } @@ -92,7 +92,7 @@ func New(config ...Config) fiber.Handler { if bytes.Contains(clientEtag, etag) { // 1 == 1 - c.Context().ResetBody() + c.RequestCtx().ResetBody() return c.SendStatus(fiber.StatusNotModified) } diff --git a/middleware/expvar/expvar.go b/middleware/expvar/expvar.go index 8ea09e1a77..bcc92c58cd 100644 --- a/middleware/expvar/expvar.go +++ b/middleware/expvar/expvar.go @@ -25,7 +25,7 @@ func New(config ...Config) fiber.Handler { return c.Next() } if path == "/debug/vars" { - expvarhandler.ExpvarHandler(c.Context()) + expvarhandler.ExpvarHandler(c.RequestCtx()) return nil } diff --git a/middleware/idempotency/idempotency.go b/middleware/idempotency/idempotency.go index 923ce5ce9a..096384638a 100644 --- a/middleware/idempotency/idempotency.go +++ b/middleware/idempotency/idempotency.go @@ -51,7 +51,7 @@ func New(config ...Config) fiber.Handler { for header, vals := range res.Headers { for _, val := range vals { - c.Context().Response.Header.Add(header, val) + c.RequestCtx().Response.Header.Add(header, val) } } diff --git a/middleware/logger/logger_test.go b/middleware/logger/logger_test.go index 0bc06531c9..ce2a83366d 100644 --- a/middleware/logger/logger_test.go +++ b/middleware/logger/logger_test.go @@ -634,7 +634,7 @@ func Test_Logger_ByteSent_Streaming(t *testing.T) { app.Get("/", func(c fiber.Ctx) error { c.Set("Connection", "keep-alive") c.Set("Transfer-Encoding", "chunked") - c.Context().SetBodyStreamWriter(func(w *bufio.Writer) { + c.RequestCtx().SetBodyStreamWriter(func(w *bufio.Writer) { var i int for { i++ @@ -805,7 +805,7 @@ func Benchmark_Logger(b *testing.B) { app.Get("/", func(c fiber.Ctx) error { c.Set("Connection", "keep-alive") c.Set("Transfer-Encoding", "chunked") - c.Context().SetBodyStreamWriter(func(w *bufio.Writer) { + c.RequestCtx().SetBodyStreamWriter(func(w *bufio.Writer) { var i int for { i++ @@ -960,7 +960,7 @@ func Benchmark_Logger_Parallel(b *testing.B) { app.Get("/", func(c fiber.Ctx) error { c.Set("Connection", "keep-alive") c.Set("Transfer-Encoding", "chunked") - c.Context().SetBodyStreamWriter(func(w *bufio.Writer) { + c.RequestCtx().SetBodyStreamWriter(func(w *bufio.Writer) { var i int for { i++ diff --git a/middleware/pprof/pprof.go b/middleware/pprof/pprof.go index 13b01b533c..a8be0c059f 100644 --- a/middleware/pprof/pprof.go +++ b/middleware/pprof/pprof.go @@ -48,27 +48,27 @@ func New(config ...Config) fiber.Handler { // Switch on trimmed path against constant strings switch path { case "/": - pprofIndex(c.Context()) + pprofIndex(c.RequestCtx()) case "/cmdline": - pprofCmdline(c.Context()) + pprofCmdline(c.RequestCtx()) case "/profile": - pprofProfile(c.Context()) + pprofProfile(c.RequestCtx()) case "/symbol": - pprofSymbol(c.Context()) + pprofSymbol(c.RequestCtx()) case "/trace": - pprofTrace(c.Context()) + pprofTrace(c.RequestCtx()) case "/allocs": - pprofAllocs(c.Context()) + pprofAllocs(c.RequestCtx()) case "/block": - pprofBlock(c.Context()) + pprofBlock(c.RequestCtx()) case "/goroutine": - pprofGoroutine(c.Context()) + pprofGoroutine(c.RequestCtx()) case "/heap": - pprofHeap(c.Context()) + pprofHeap(c.RequestCtx()) case "/mutex": - pprofMutex(c.Context()) + pprofMutex(c.RequestCtx()) case "/threadcreate": - pprofThreadcreate(c.Context()) + pprofThreadcreate(c.RequestCtx()) default: // pprof index only works with trailing slash if strings.HasSuffix(path, "/") { diff --git a/middleware/redirect/redirect.go b/middleware/redirect/redirect.go index 4fb7bb8830..0e95095dd3 100644 --- a/middleware/redirect/redirect.go +++ b/middleware/redirect/redirect.go @@ -30,7 +30,7 @@ func New(config ...Config) fiber.Handler { for k, v := range cfg.rulesRegex { replacer := captureTokens(k, c.Path()) if replacer != nil { - queryString := string(c.Context().QueryArgs().QueryString()) + queryString := string(c.RequestCtx().QueryArgs().QueryString()) if queryString != "" { queryString = "?" + queryString } diff --git a/middleware/static/static.go b/middleware/static/static.go index 6cbdbd3d22..7afc77980f 100644 --- a/middleware/static/static.go +++ b/middleware/static/static.go @@ -114,7 +114,7 @@ func New(root string, cfg ...Config) fiber.Handler { }) // Serve file - fileHandler(c.Context()) + fileHandler(c.RequestCtx()) // Sets the response Content-Disposition header to attachment if the Download option is true if config.Download { @@ -122,11 +122,11 @@ func New(root string, cfg ...Config) fiber.Handler { } // Return request if found and not forbidden - status := c.Context().Response.StatusCode() + status := c.RequestCtx().Response.StatusCode() if status != fiber.StatusNotFound && status != fiber.StatusForbidden { if len(cacheControlValue) > 0 { - c.Context().Response.Header.Set(fiber.HeaderCacheControl, cacheControlValue) + c.RequestCtx().Response.Header.Set(fiber.HeaderCacheControl, cacheControlValue) } if config.ModifyResponse != nil { @@ -142,9 +142,9 @@ func New(root string, cfg ...Config) fiber.Handler { } // Reset response to default - c.Context().SetContentType("") // Issue #420 - c.Context().Response.SetStatusCode(fiber.StatusOK) - c.Context().Response.SetBodyString("") + c.RequestCtx().SetContentType("") // Issue #420 + c.RequestCtx().Response.SetStatusCode(fiber.StatusOK) + c.RequestCtx().Response.SetBodyString("") // Next middleware return c.Next() diff --git a/middleware/timeout/timeout.go b/middleware/timeout/timeout.go index 5a9711ce22..a88f2e90b1 100644 --- a/middleware/timeout/timeout.go +++ b/middleware/timeout/timeout.go @@ -11,9 +11,9 @@ import ( // New implementation of timeout middleware. Set custom errors(context.DeadlineExceeded vs) for get fiber.ErrRequestTimeout response. func New(h fiber.Handler, t time.Duration, tErrs ...error) fiber.Handler { return func(ctx fiber.Ctx) error { - timeoutContext, cancel := context.WithTimeout(ctx.UserContext(), t) + timeoutContext, cancel := context.WithTimeout(ctx.Context(), t) defer cancel() - ctx.SetUserContext(timeoutContext) + ctx.SetContext(timeoutContext) if err := h(ctx); err != nil { if errors.Is(err, context.DeadlineExceeded) { return fiber.ErrRequestTimeout diff --git a/middleware/timeout/timeout_test.go b/middleware/timeout/timeout_test.go index b08445eb2a..2e1756184c 100644 --- a/middleware/timeout/timeout_test.go +++ b/middleware/timeout/timeout_test.go @@ -20,7 +20,7 @@ func Test_WithContextTimeout(t *testing.T) { h := New(func(c fiber.Ctx) error { sleepTime, err := time.ParseDuration(c.Params("sleepTime") + "ms") require.NoError(t, err) - if err := sleepWithContext(c.UserContext(), sleepTime, context.DeadlineExceeded); err != nil { + if err := sleepWithContext(c.Context(), sleepTime, context.DeadlineExceeded); err != nil { return fmt.Errorf("%w: l2 wrap", fmt.Errorf("%w: l1 wrap ", err)) } return nil @@ -52,7 +52,7 @@ func Test_WithContextTimeoutWithCustomError(t *testing.T) { h := New(func(c fiber.Ctx) error { sleepTime, err := time.ParseDuration(c.Params("sleepTime") + "ms") require.NoError(t, err) - if err := sleepWithContext(c.UserContext(), sleepTime, ErrFooTimeOut); err != nil { + if err := sleepWithContext(c.Context(), sleepTime, ErrFooTimeOut); err != nil { return fmt.Errorf("%w: execution error", err) } return nil diff --git a/redirect.go b/redirect.go index ebbcb499b8..bc79314922 100644 --- a/redirect.go +++ b/redirect.go @@ -141,7 +141,7 @@ func (r *Redirect) With(key, value string, level ...uint8) *Redirect { // You can get them by using: Redirect().OldInputs(), Redirect().OldInput() func (r *Redirect) WithInput() *Redirect { // Get content-type - ctype := utils.ToLower(utils.UnsafeString(r.c.Context().Request.Header.ContentType())) + ctype := utils.ToLower(utils.UnsafeString(r.c.RequestCtx().Request.Header.ContentType())) ctype = binder.FilterFlags(utils.ParseVendorSpecificContentType(ctype)) oldInput := make(map[string]string) diff --git a/redirect_test.go b/redirect_test.go index 7544aec01d..1570d05fbf 100644 --- a/redirect_test.go +++ b/redirect_test.go @@ -42,7 +42,7 @@ func Test_Redirect_To_WithFlashMessages(t *testing.T) { require.Equal(t, 302, c.Response().StatusCode()) require.Equal(t, "http://example.com", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -185,7 +185,7 @@ func Test_Redirect_Back_WithFlashMessages(t *testing.T) { require.Equal(t, 302, c.Response().StatusCode()) require.Equal(t, "/", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -236,7 +236,7 @@ func Test_Redirect_Route_WithFlashMessages(t *testing.T) { require.Equal(t, 302, c.Response().StatusCode()) require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -273,7 +273,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) { require.Equal(t, 302, c.Response().StatusCode()) require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -309,7 +309,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) { require.Equal(t, 302, c.Response().StatusCode()) require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -353,7 +353,7 @@ func Test_Redirect_Route_WithOldInput(t *testing.T) { require.Equal(t, 302, c.Response().StatusCode()) require.Equal(t, "/user", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -538,7 +538,7 @@ func Benchmark_Redirect_Route_WithFlashMessages(b *testing.B) { require.Equal(b, 302, c.Response().StatusCode()) require.Equal(b, "/user", string(c.Response().Header.Peek(HeaderLocation))) - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err = msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName))) @@ -629,7 +629,7 @@ func Benchmark_Redirect_processFlashMessages(b *testing.B) { c.Redirect().processFlashMessages() } - c.Context().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing + c.RequestCtx().Request.Header.Set(HeaderCookie, c.GetRespHeader(HeaderSetCookie)) // necessary for testing var msgs redirectionMsgs _, err := msgs.UnmarshalMsg([]byte(c.Cookies(FlashCookieName)))