Files
appcore/request/query.go

56 lines
1.2 KiB
Go
Raw Normal View History

2025-06-16 22:19:00 +05:30
// Copyright 2024 Patial Tech (Ankit Patial).
2025-06-16 22:26:47 +05:30
//
// This file is part of code.patial.tech/go/appcore, which is MIT licensed.
// See http://opensource.org/licenses/MIT
2025-06-16 22:19:00 +05:30
package request
import (
"fmt"
"net/http"
"reflect"
"strconv"
)
type Number interface {
int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64 | float32 | float64
}
// NumberParam from request query string
func NumberParam[T Number](r *http.Request, key string) (T, error) {
var noop T
2026-02-20 16:54:14 +05:30
q := r.URL.Query()
if !q.Has(key) {
2025-06-16 22:19:00 +05:30
return noop, fmt.Errorf("query param: %q is missing", key)
}
2026-02-20 16:54:14 +05:30
p := q.Get(key)
k := reflect.TypeOf(noop).Kind()
2025-06-16 22:19:00 +05:30
// float param
if k == reflect.Float32 || k == reflect.Float64 {
n, err := strconv.ParseFloat(p, 64)
if err != nil {
return noop, fmt.Errorf("query param: %q is not a valid float", key)
}
return T(n), nil
}
2026-02-20 16:38:24 +05:30
// unsigned int param
if k >= reflect.Uint && k <= reflect.Uint64 {
n, err := strconv.ParseUint(p, 10, 64)
if err != nil {
return noop, fmt.Errorf("query param: %q is not a valid unsigned integer", key)
}
return T(n), nil
}
// signed int param
2025-06-16 22:19:00 +05:30
n, err := strconv.ParseInt(p, 10, 64)
if err != nil {
return noop, fmt.Errorf("query param: %q is not a valid integer", key)
}
2026-02-20 16:38:24 +05:30
2025-06-16 22:19:00 +05:30
return T(n), nil
}