re-use r.URL.Query

This commit is contained in:
2026-02-20 16:54:14 +05:30
parent f1601020b1
commit 3c4d1b464c
2 changed files with 12 additions and 10 deletions

View File

@@ -57,23 +57,25 @@ func (i *Pager) Limit() int {
// GetPager info from request's query parameters // GetPager info from request's query parameters
func GetPager(r *http.Request) Pager { func GetPager(r *http.Request) Pager {
q := r.URL.Query()
p := Pager{ p := Pager{
Page: 1, Page: 1,
Size: 20, Size: 20,
OrderAsc: new(true), OrderAsc: new(true),
} }
if v := r.URL.Query().Get("q"); v != "" { if v := q.Get("q"); v != "" {
p.Search = strings.TrimSpace(v) p.Search = strings.TrimSpace(v)
} }
if v := r.URL.Query().Get("pg"); v != "" { if v := q.Get("pg"); v != "" {
if vv, err := strconv.Atoi(v); err == nil && vv > 0 { if vv, err := strconv.Atoi(v); err == nil && vv > 0 {
p.Page = vv p.Page = vv
} }
} }
if v := r.URL.Query().Get("pg_s"); v != "" { if v := q.Get("pg_s"); v != "" {
if vv, err := strconv.Atoi(v); err == nil && vv > 0 { if vv, err := strconv.Atoi(v); err == nil && vv > 0 {
if vv > MaxPageSize { if vv > MaxPageSize {
vv = MaxPageSize vv = MaxPageSize
@@ -82,11 +84,11 @@ func GetPager(r *http.Request) Pager {
} }
} }
if v := r.URL.Query().Get("pg_ob"); v != "" { if v := q.Get("pg_ob"); v != "" {
p.OrderBy = &v p.OrderBy = &v
} }
if v := r.URL.Query().Get("pg_o"); v != "" { if v := q.Get("pg_o"); v != "" {
switch strings.ToLower(v) { switch strings.ToLower(v) {
case "asc": case "asc":
p.OrderAsc = new(true) p.OrderAsc = new(true)
@@ -95,7 +97,7 @@ func GetPager(r *http.Request) Pager {
} }
} }
if v := r.URL.Query().Get("pg_t"); v == "n" { if v := q.Get("pg_t"); v == "n" {
p.TotalNeeded = true p.TotalNeeded = true
} }

View File

@@ -19,13 +19,13 @@ type Number interface {
// NumberParam from request query string // NumberParam from request query string
func NumberParam[T Number](r *http.Request, key string) (T, error) { func NumberParam[T Number](r *http.Request, key string) (T, error) {
var noop T var noop T
if !r.URL.Query().Has(key) { q := r.URL.Query()
if !q.Has(key) {
return noop, fmt.Errorf("query param: %q is missing", key) return noop, fmt.Errorf("query param: %q is missing", key)
} }
p := r.URL.Query().Get(key) p := q.Get(key)
t := reflect.TypeOf(noop) k := reflect.TypeOf(noop).Kind()
k := t.Kind()
// float param // float param
if k == reflect.Float32 || k == reflect.Float64 { if k == reflect.Float32 || k == reflect.Float64 {
n, err := strconv.ParseFloat(p, 64) n, err := strconv.ParseFloat(p, 64)