fiber/ctx_interface.go
nickajacks1 64c1771c26
🔥 Feature: Add Req and Res API (#2894)
* 🔥 feat: add Req and Res interfaces

Split the existing Ctx API into two separate APIs for Requests and
Responses. There are two goals to this change:

1. Reduce cognitive load by making it more obvious whether a Ctx method
   interacts with the request or the response.
2. Increase API parity with Express.

* fix(req,res): several issues

* Sprinkle in calls to Req() and Res() to a few unit tests
* Fix improper initialization caught by ^
* Add a few missing methods

* docs: organize Ctx methods by request and response

* feat(req,res): sync more missed methods

---------

Co-authored-by: Juan Calderon-Perez <835733+gaby@users.noreply.github.com>
2025-03-05 08:01:43 +01:00

74 lines
1.4 KiB
Go

// ⚡️ Fiber is an Express inspired web framework written in Go with ☕️
// 🤖 Github Repository: https://github.com/gofiber/fiber
// 📌 API Documentation: https://docs.gofiber.io
package fiber
import (
"errors"
"github.com/valyala/fasthttp"
)
type CustomCtx interface {
Ctx
// Reset is a method to reset context fields by given request when to use server handlers.
Reset(fctx *fasthttp.RequestCtx)
// Methods to use with next stack.
getMethodINT() int
getIndexRoute() int
getTreePath() string
getDetectionPath() string
getPathOriginal() string
getValues() *[maxParams]string
getMatched() bool
setIndexHandler(handler int)
setIndexRoute(route int)
setMatched(matched bool)
setRoute(route *Route)
}
func NewDefaultCtx(app *App) *DefaultCtx {
// return ctx
ctx := &DefaultCtx{
// Set app reference
app: app,
}
ctx.req = &DefaultReq{ctx: ctx}
ctx.res = &DefaultRes{ctx: ctx}
return ctx
}
func (app *App) newCtx() Ctx {
var c Ctx
if app.newCtxFunc != nil {
c = app.newCtxFunc(app)
} else {
c = NewDefaultCtx(app)
}
return c
}
// AcquireCtx retrieves a new Ctx from the pool.
func (app *App) AcquireCtx(fctx *fasthttp.RequestCtx) Ctx {
ctx, ok := app.pool.Get().(Ctx)
if !ok {
panic(errors.New("failed to type-assert to Ctx"))
}
ctx.Reset(fctx)
return ctx
}
// ReleaseCtx releases the ctx back into the pool.
func (app *App) ReleaseCtx(c Ctx) {
c.release()
app.pool.Put(c)
}