simplify data access in ctx

This commit is contained in:
Sky Johnson 2025-09-12 13:58:54 -05:00
parent 4bad13510a
commit a2c782c54a
4 changed files with 16 additions and 16 deletions

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -8,6 +8,7 @@ import (
type Ctx struct {
*fasthttp.RequestCtx
Params []string
}
type Handler func(ctx Ctx)