all repos — telegram-bot-api @ 5875a46cdedea21de70ec6f5b4d4825bb1fe6f6e

Golang bindings for the Telegram Bot API

params.go (view raw)

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