all repos — telegram-bot-api @ 797f683a71269be25db71133e60c82e96c8e0725

Golang bindings for the Telegram Bot API

params.go (view raw)

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