github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/bft/rpc/lib/server/http_params.go (about)

     1  package rpcserver
     2  
     3  import (
     4  	"encoding/hex"
     5  	"net/http"
     6  	"regexp"
     7  	"strconv"
     8  
     9  	"github.com/gnolang/gno/tm2/pkg/errors"
    10  )
    11  
    12  func GetParam(r *http.Request, param string) string {
    13  	s := r.URL.Query().Get(param)
    14  	if s == "" {
    15  		s = r.FormValue(param)
    16  	}
    17  	return s
    18  }
    19  
    20  func GetParamByteSlice(r *http.Request, param string) ([]byte, error) {
    21  	s := GetParam(r, param)
    22  	return hex.DecodeString(s)
    23  }
    24  
    25  func GetParamInt64(r *http.Request, param string) (int64, error) {
    26  	s := GetParam(r, param)
    27  	i, err := strconv.ParseInt(s, 10, 64)
    28  	if err != nil {
    29  		return 0, errors.New(param, err.Error())
    30  	}
    31  	return i, nil
    32  }
    33  
    34  func GetParamInt32(r *http.Request, param string) (int32, error) {
    35  	s := GetParam(r, param)
    36  	i, err := strconv.ParseInt(s, 10, 32)
    37  	if err != nil {
    38  		return 0, errors.New(param, err.Error())
    39  	}
    40  	return int32(i), nil
    41  }
    42  
    43  func GetParamUint64(r *http.Request, param string) (uint64, error) {
    44  	s := GetParam(r, param)
    45  	i, err := strconv.ParseUint(s, 10, 64)
    46  	if err != nil {
    47  		return 0, errors.New(param, err.Error())
    48  	}
    49  	return i, nil
    50  }
    51  
    52  func GetParamUint(r *http.Request, param string) (uint, error) {
    53  	s := GetParam(r, param)
    54  	i, err := strconv.ParseUint(s, 10, 64)
    55  	if err != nil {
    56  		return 0, errors.New(param, err.Error())
    57  	}
    58  	return uint(i), nil
    59  }
    60  
    61  func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
    62  	s := GetParam(r, param)
    63  	if !re.MatchString(s) {
    64  		return "", errors.New(param, "did not match regular expression %v", re.String())
    65  	}
    66  	return s, nil
    67  }
    68  
    69  func GetParamFloat64(r *http.Request, param string) (float64, error) {
    70  	s := GetParam(r, param)
    71  	f, err := strconv.ParseFloat(s, 64)
    72  	if err != nil {
    73  		return 0, errors.New(param, err.Error())
    74  	}
    75  	return f, nil
    76  }