David K. Bainbridge | 528b318 | 2017-01-23 08:51:59 -0800 | [diff] [blame] | 1 | // Copyright 2016 Canonical Ltd. |
| 2 | // Licensed under the LGPLv3, see LICENCE file for details. |
| 3 | |
| 4 | package gomaasapi |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "net/url" |
| 9 | ) |
| 10 | |
| 11 | // URLParams wraps url.Values to easily add values, but skipping empty ones. |
| 12 | type URLParams struct { |
| 13 | Values url.Values |
| 14 | } |
| 15 | |
| 16 | // NewURLParams allocates a new URLParams type. |
| 17 | func NewURLParams() *URLParams { |
| 18 | return &URLParams{Values: make(url.Values)} |
| 19 | } |
| 20 | |
| 21 | // MaybeAdd adds the (name, value) pair iff value is not empty. |
| 22 | func (p *URLParams) MaybeAdd(name, value string) { |
| 23 | if value != "" { |
| 24 | p.Values.Add(name, value) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | // MaybeAddInt adds the (name, value) pair iff value is not zero. |
| 29 | func (p *URLParams) MaybeAddInt(name string, value int) { |
| 30 | if value != 0 { |
| 31 | p.Values.Add(name, fmt.Sprint(value)) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | // MaybeAddBool adds the (name, value) pair iff value is true. |
| 36 | func (p *URLParams) MaybeAddBool(name string, value bool) { |
| 37 | if value { |
| 38 | p.Values.Add(name, fmt.Sprint(value)) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | // MaybeAddMany adds the (name, value) for each value in values iff |
| 43 | // value is not empty. |
| 44 | func (p *URLParams) MaybeAddMany(name string, values []string) { |
| 45 | for _, value := range values { |
| 46 | p.MaybeAdd(name, value) |
| 47 | } |
| 48 | } |