all repos — telegram-bot-api @ aaaa278b563e4e344a0e9440591347371801f2f1

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// AddNonNilBool adds the value of a bool pointer if not nil.
 41func (p Params) AddNonNilBool(key string, value *bool) {
 42	if value != nil {
 43		p[key] = strconv.FormatBool(*value)
 44	}
 45}
 46
 47// AddNonZeroFloat adds a floating point value that is not zero.
 48func (p Params) AddNonZeroFloat(key string, value float64) {
 49	if value != 0 {
 50		p[key] = strconv.FormatFloat(value, 'f', 6, 64)
 51	}
 52}
 53
 54// AddInterface adds an interface if it is not nill and can be JSON marshalled.
 55func (p Params) AddInterface(key string, value interface{}) error {
 56	if value == nil || (reflect.ValueOf(value).Kind() == reflect.Ptr && reflect.ValueOf(value).IsNil()) {
 57		return nil
 58	}
 59
 60	b, err := json.Marshal(value)
 61	if err != nil {
 62		return err
 63	}
 64
 65	p[key] = string(b)
 66
 67	return nil
 68}
 69
 70// AddFirstValid attempts to add the first item that is not a default value.
 71//
 72// For example, AddFirstValid(0, "", "test") would add "test".
 73func (p Params) AddFirstValid(key string, args ...interface{}) error {
 74	for _, arg := range args {
 75		switch v := arg.(type) {
 76		case int:
 77			if v != 0 {
 78				p[key] = strconv.Itoa(v)
 79			}
 80		case int64:
 81			if v != 0 {
 82				p[key] = strconv.FormatInt(v, 10)
 83			}
 84		case string:
 85			if v != "" {
 86				p[key] = v
 87			}
 88		case nil:
 89		default:
 90			b, err := json.Marshal(arg)
 91			if err != nil {
 92				return err
 93			}
 94
 95			p[key] = string(b)
 96		}
 97	}
 98
 99	return nil
100}