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.

91 lines
2.2 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_INT = regexp.MustCompile(`^-?[0-9]+$`)
  15. RE_HEX = regexp.MustCompile(`^(?i)[a-f0-9]+$`)
  16. RE_EMAIL = regexp.MustCompile(`^(?i)(` + dotAtom + `)@(` + dotAtom + `)$`)
  17. RE_ADDRESS = regexp.MustCompile(`^(?i)[a-z0-9]{25,34}$`)
  18. RE_HOST = regexp.MustCompile(`^(?i)(` + domain + `)$`)
  19. //RE_ID12 = regexp.MustCompile(`^[a-zA-Z0-9]{12}$`)
  20. )
  21. func GetParam(r *http.Request, param string) string {
  22. s := r.URL.Query().Get(param)
  23. if s == "" {
  24. s = r.FormValue(param)
  25. }
  26. return s
  27. }
  28. func GetParamByteSlice(r *http.Request, param string) ([]byte, error) {
  29. s := GetParam(r, param)
  30. return hex.DecodeString(s)
  31. }
  32. func GetParamInt64(r *http.Request, param string) (int64, error) {
  33. s := GetParam(r, param)
  34. i, err := strconv.ParseInt(s, 10, 64)
  35. if err != nil {
  36. return 0, errors.Errorf(param, err.Error())
  37. }
  38. return i, nil
  39. }
  40. func GetParamInt32(r *http.Request, param string) (int32, error) {
  41. s := GetParam(r, param)
  42. i, err := strconv.ParseInt(s, 10, 32)
  43. if err != nil {
  44. return 0, errors.Errorf(param, err.Error())
  45. }
  46. return int32(i), nil
  47. }
  48. func GetParamUint64(r *http.Request, param string) (uint64, error) {
  49. s := GetParam(r, param)
  50. i, err := strconv.ParseUint(s, 10, 64)
  51. if err != nil {
  52. return 0, errors.Errorf(param, err.Error())
  53. }
  54. return i, nil
  55. }
  56. func GetParamUint(r *http.Request, param string) (uint, error) {
  57. s := GetParam(r, param)
  58. i, err := strconv.ParseUint(s, 10, 64)
  59. if err != nil {
  60. return 0, errors.Errorf(param, err.Error())
  61. }
  62. return uint(i), nil
  63. }
  64. func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
  65. s := GetParam(r, param)
  66. if !re.MatchString(s) {
  67. return "", errors.Errorf(param, "Did not match regular expression %v", re.String())
  68. }
  69. return s, nil
  70. }
  71. func GetParamFloat64(r *http.Request, param string) (float64, error) {
  72. s := GetParam(r, param)
  73. f, err := strconv.ParseFloat(s, 64)
  74. if err != nil {
  75. return 0, errors.Errorf(param, err.Error())
  76. }
  77. return f, nil
  78. }