params.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. package tgbotapi
  2. import (
  3. "encoding/json"
  4. "reflect"
  5. "strconv"
  6. )
  7. // Params represents a set of parameters that gets passed to a request.
  8. type Params map[string]string
  9. // AddNonEmpty adds a value if it not an empty string.
  10. func (p Params) AddNonEmpty(key, value string) {
  11. if value != "" {
  12. p[key] = value
  13. }
  14. }
  15. // AddNonZero adds a value if it is not zero.
  16. func (p Params) AddNonZero(key string, value int) {
  17. if value != 0 {
  18. p[key] = strconv.Itoa(value)
  19. }
  20. }
  21. // AddNonZero64 is the same as AddNonZero except uses an int64.
  22. func (p Params) AddNonZero64(key string, value int64) {
  23. if value != 0 {
  24. p[key] = strconv.FormatInt(value, 10)
  25. }
  26. }
  27. // AddBool adds a value of a bool if it is true.
  28. func (p Params) AddBool(key string, value bool) {
  29. if value {
  30. p[key] = strconv.FormatBool(value)
  31. }
  32. }
  33. // AddNonZeroFloat adds a floating point value that is not zero.
  34. func (p Params) AddNonZeroFloat(key string, value float64) {
  35. if value != 0 {
  36. p[key] = strconv.FormatFloat(value, 'f', 6, 64)
  37. }
  38. }
  39. // AddInterface adds an interface if it is not nil and can be JSON marshalled.
  40. func (p Params) AddInterface(key string, value interface{}) error {
  41. if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
  42. return nil
  43. }
  44. b, err := json.Marshal(value)
  45. if err != nil {
  46. return err
  47. }
  48. p[key] = string(b)
  49. return nil
  50. }
  51. // AddFirstValid attempts to add the first item that is not a default value.
  52. //
  53. // For example, AddFirstValid(0, "", "test") would add "test".
  54. func (p Params) AddFirstValid(key string, args ...interface{}) error {
  55. for _, arg := range args {
  56. switch v := arg.(type) {
  57. case int:
  58. if v != 0 {
  59. p[key] = strconv.Itoa(v)
  60. return nil
  61. }
  62. case int64:
  63. if v != 0 {
  64. p[key] = strconv.FormatInt(v, 10)
  65. return nil
  66. }
  67. case string:
  68. if v != "" {
  69. p[key] = v
  70. return nil
  71. }
  72. case nil:
  73. default:
  74. b, err := json.Marshal(arg)
  75. if err != nil {
  76. return err
  77. }
  78. p[key] = string(b)
  79. return nil
  80. }
  81. }
  82. return nil
  83. }