basic common app packages
This commit is contained in:
42
request/query.go
Normal file
42
request/query.go
Normal file
@@ -0,0 +1,42 @@
|
||||
// Copyright 2024 Patial Tech (Ankit Patial).
|
||||
// All rights reserved.
|
||||
|
||||
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
|
||||
if !r.URL.Query().Has(key) {
|
||||
return noop, fmt.Errorf("query param: %q is missing", key)
|
||||
}
|
||||
|
||||
p := r.URL.Query().Get(key)
|
||||
t := reflect.TypeOf(noop)
|
||||
k := t.Kind()
|
||||
// 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
|
||||
}
|
||||
|
||||
// int param
|
||||
n, err := strconv.ParseInt(p, 10, 64)
|
||||
if err != nil {
|
||||
return noop, fmt.Errorf("query param: %q is not a valid integer", key)
|
||||
}
|
||||
return T(n), nil
|
||||
}
|
Reference in New Issue
Block a user