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.

94 lines
2.2 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. package rpc
  2. import (
  3. "encoding/hex"
  4. "net/http"
  5. "regexp"
  6. "strconv"
  7. . "github.com/tendermint/tendermint2/common"
  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 panicAPI(err error) {
  21. panic(APIResponse{API_INVALID_PARAM, nil, err.Error()})
  22. }
  23. func GetParam(r *http.Request, param string) string {
  24. s := r.URL.Query().Get(param)
  25. if s == "" {
  26. s = r.FormValue(param)
  27. }
  28. return s
  29. }
  30. func GetParamByteSlice(r *http.Request, param string) ([]byte, error) {
  31. s := GetParam(r, param)
  32. return hex.DecodeString(s)
  33. }
  34. func GetParamInt64(r *http.Request, param string) (int64, error) {
  35. s := GetParam(r, param)
  36. i, err := strconv.ParseInt(s, 10, 64)
  37. if err != nil {
  38. return 0, Errorf(param, err.Error())
  39. }
  40. return i, nil
  41. }
  42. func GetParamInt32(r *http.Request, param string) (int32, error) {
  43. s := GetParam(r, param)
  44. i, err := strconv.ParseInt(s, 10, 32)
  45. if err != nil {
  46. return 0, Errorf(param, err.Error())
  47. }
  48. return int32(i), nil
  49. }
  50. func GetParamUint64(r *http.Request, param string) (uint64, error) {
  51. s := GetParam(r, param)
  52. i, err := strconv.ParseUint(s, 10, 64)
  53. if err != nil {
  54. return 0, Errorf(param, err.Error())
  55. }
  56. return i, nil
  57. }
  58. func GetParamUint(r *http.Request, param string) (uint, error) {
  59. s := GetParam(r, param)
  60. i, err := strconv.ParseUint(s, 10, 64)
  61. if err != nil {
  62. return 0, Errorf(param, err.Error())
  63. }
  64. return uint(i), nil
  65. }
  66. func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) {
  67. s := GetParam(r, param)
  68. if !re.MatchString(s) {
  69. return "", Errorf(param, "Did not match regular expression %v", re.String())
  70. }
  71. return s, nil
  72. }
  73. func GetParamFloat64(r *http.Request, param string) (float64, error) {
  74. s := GetParam(r, param)
  75. f, err := strconv.ParseFloat(s, 64)
  76. if err != nil {
  77. return 0, Errorf(param, err.Error())
  78. }
  79. return f, nil
  80. }