From a2c782c54a5540c71ee1a4d9518e9a2892ecbbb7 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Fri, 12 Sep 2025 13:58:54 -0500 Subject: [PATCH] simplify data access in ctx --- forms.go | 9 +++++++-- params.go | 18 +++++++----------- router.go | 4 +--- types.go | 1 + 4 files changed, 16 insertions(+), 16 deletions(-) diff --git a/forms.go b/forms.go index d91dc55..636a6c3 100644 --- a/forms.go +++ b/forms.go @@ -10,13 +10,18 @@ type FormValue struct { exists bool } -// Form gets a form field for chaining -func (ctx Ctx) Form(key string) FormValue { +// Input gets a form field for chaining +func (ctx Ctx) Input(key string) FormValue { value := string(ctx.PostArgs().Peek(key)) exists := ctx.PostArgs().Has(key) return FormValue{value: value, exists: exists} } +// Form gets a form field for chaining (deprecated: use Input instead) +func (ctx Ctx) Form(key string) FormValue { + return ctx.Input(key) +} + // String returns the value as string func (f FormValue) String() string { return f.value diff --git a/params.go b/params.go index d4c9144..9cd43a7 100644 --- a/params.go +++ b/params.go @@ -5,23 +5,12 @@ import ( "strings" ) -const RouteParamsCtxKey = "route_params" type ParamValue struct { value string exists bool } -// RouteParam gets a route parameter by index for chaining -func (ctx Ctx) RouteParam(index int) ParamValue { - if params, ok := ctx.UserValue(RouteParamsCtxKey).([]string); ok { - if index >= 0 && index < len(params) { - return ParamValue{value: params[index], exists: true} - } - } - return ParamValue{value: "", exists: false} -} - // Param gets a route parameter by name for chaining (requires named params) func (ctx Ctx) Param(name string) ParamValue { if paramMap, ok := ctx.UserValue("param_names").(map[string]string); ok { @@ -32,6 +21,13 @@ func (ctx Ctx) Param(name string) ParamValue { return ParamValue{value: "", exists: false} } +// Query gets a query parameter for chaining +func (ctx Ctx) Query(key string) ParamValue { + value := string(ctx.QueryArgs().Peek(key)) + exists := ctx.QueryArgs().Has(key) + return ParamValue{value: value, exists: exists} +} + // String returns the value as string func (p ParamValue) String() string { return p.value diff --git a/router.go b/router.go index 944881a..4581cae 100644 --- a/router.go +++ b/router.go @@ -57,10 +57,8 @@ func (r *Router) ServeHTTP(ctx *fasthttp.RequestCtx) { } // Store params in context - sushiCtx := Ctx{ctx} + sushiCtx := Ctx{RequestCtx: ctx, Params: params} if len(params) > 0 { - sushiCtx.SetUserValue(RouteParamsCtxKey, params) - // Create named param map if param names exist if len(paramNames) > 0 { paramMap := make(map[string]string) diff --git a/types.go b/types.go index ba6c033..8108568 100644 --- a/types.go +++ b/types.go @@ -8,6 +8,7 @@ import ( type Ctx struct { *fasthttp.RequestCtx + Params []string } type Handler func(ctx Ctx)