You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.1 KiB

  1. package rpcserver
  2. import (
  3. "encoding/hex"
  4. "net/http"
  5. "regexp"
  6. "strconv"
  7. "github.com/pkg/errors"
  8. )
  9. var (
  10. // Parts of regular expressions
  11. atom = "[A-Z0-9!#$%&'*+\\-/=?^_`{|}~]+"
  12. dotAtom = atom + `(?:\.` + atom + `)*`
  13. domain = `[A-Z0-9.-]+\.[A-Z]{2,4}`
  14. RE_HEX = regexp.MustCompile(`^(?i)[a-f0-9]+$`)
  15. RE_EMAIL = regexp.MustCompile(`^(?i)(` + dotAtom + `)@(` + dotAtom + `)$`)
  16. RE_ADDRESS = regexp.MustCompile(`^(?i)[a-z0-9]{25,34}$`)
  17. RE_HOST = regexp.MustCompile(`^(?i)(` + domain + `)$`)
  18. //RE_ID12 = regexp.MustCompile(`^[a-zA-Z0-9]{12}$`)
  19. )
  20. func GetParam(r *http.Request, param string) string {
  21. s := r.URL.Query().Get(param)
  22. if s == "" {
  23. s = r.FormValue(param)
  24. }
  25. return s
  26. }
  27. func GetParamByteSlice(r *http.Request, param string) ([]byte, error) {
  28. s := GetParam(r, param)
  29. return hex.DecodeString(s)
  30. }
  31. func GetParamInt64(r *http.Request, param string) (int64, error) {
  32. s := GetParam(r, param)
  33. i, err := strconv.ParseInt(s, 10, 64)
  34. if err != nil {
  35. return 0, errors.Errorf(param, err.Error())
  36. }
  37. return i, nil
  38. }
  39. func GetParamInt32(r *http.Request, param string) (int32, error) {
  40. s := GetParam(r, param)
  41. i, err := strconv.ParseInt(s, 10, 32)
  42. if err != nil {
  43. return 0, errors.Errorf(param, err.Error())
  44. }
  45. return int32(i), nil
  46. }
  47. func GetParamUint64(r *http.Request, param string) (uint64, error) {
  48. s := GetParam(r, param)
  49. i, err := strconv.ParseUint(s, 10, 64)
  50. if err != nil {
  51. return 0, errors.Errorf(param, err.Error())
  52. }
  53. return i, nil
  54. }
  55. func GetParamUint(r *http.Request, param string) (uint, error) {
  56. s := GetParam(r, param)
  57. i, err := strconv.ParseUint(s, 10, 64)
  58. if err != nil {
  59. return 0, errors.Errorf(param, err.Error())
  60. }
  61. return uint(i), nil
  62. }
  63. func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
  64. s := GetParam(r, param)
  65. if !re.MatchString(s) {
  66. return "", errors.Errorf(param, "Did not match regular expression %v", re.String())
  67. }
  68. return s, nil
  69. }
  70. func GetParamFloat64(r *http.Request, param string) (float64, error) {
  71. s := GetParam(r, param)
  72. f, err := strconv.ParseFloat(s, 64)
  73. if err != nil {
  74. return 0, errors.Errorf(param, err.Error())
  75. }
  76. return f, nil
  77. }