// Copyright 2024 Patial Tech (Ankit Patial). // // This file is part of code.patial.tech/go/appcore, which is MIT licensed. // See http://opensource.org/licenses/MIT 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 }