blob: 948783b07389b83d56c6a06d623cbff47167d0b9 [file] [log] [blame]
Jamie Hannaford6abf9282014-09-24 10:54:13 +02001package gophercloud
2
Jon Perrittf90a43c2014-09-28 20:09:46 -05003import (
4 "fmt"
5 "net/url"
6 "reflect"
7 "strconv"
8 "strings"
9 "time"
10)
11
Jamie Hannafordd1e6e762014-11-06 14:26:31 +010012// EnabledState is a convenience type, mostly used in Create and Update
13// operations. Because the zero value of a bool is FALSE, we need to use a
14// pointer instead to indicate zero-ness.
15type EnabledState *bool
16
17// Convenience vars for EnabledState values.
18var (
19 iTrue = true
20 iFalse = false
21
22 Enabled EnabledState = &iTrue
23 Disabled EnabledState = &iFalse
24)
25
Jamie Hannaford7fa27892014-11-07 15:11:20 +010026// IntToPointer is a function for converting integers into integer pointers.
27// This is useful when passing in options to operations.
28func IntToPointer(i int) *int {
29 return &i
30}
31
Ash Wilson0735acb2014-10-31 14:18:00 -040032/*
33MaybeString is an internal function to be used by request methods in individual
34resource packages.
35
36It takes a string that might be a zero value and returns either a pointer to its
37address or nil. This is useful for allowing users to conveniently omit values
Ash Wilson07d1cfb2014-10-31 14:21:26 -040038from an options struct by leaving them zeroed, but still pass nil to the JSON
39serializer so they'll be omitted from the request body.
Ash Wilson0735acb2014-10-31 14:18:00 -040040*/
Jamie Hannaford6abf9282014-09-24 10:54:13 +020041func MaybeString(original string) *string {
42 if original != "" {
43 return &original
44 }
45 return nil
46}
Jon Perrittf90a43c2014-09-28 20:09:46 -050047
Ash Wilson0735acb2014-10-31 14:18:00 -040048/*
49MaybeInt is an internal function to be used by request methods in individual
50resource packages.
51
Ash Wilson07d1cfb2014-10-31 14:21:26 -040052Like MaybeString, it accepts an int that may or may not be a zero value, and
53returns either a pointer to its address or nil. It's intended to hint that the
54JSON serializer should omit its field.
Ash Wilson0735acb2014-10-31 14:18:00 -040055*/
Jon Perritt8d262582014-10-03 11:11:46 -050056func MaybeInt(original int) *int {
57 if original != 0 {
58 return &original
59 }
60 return nil
61}
62
Jon Perrittf90a43c2014-09-28 20:09:46 -050063var t time.Time
64
65func isZero(v reflect.Value) bool {
66 switch v.Kind() {
67 case reflect.Func, reflect.Map, reflect.Slice:
68 return v.IsNil()
69 case reflect.Array:
70 z := true
71 for i := 0; i < v.Len(); i++ {
72 z = z && isZero(v.Index(i))
73 }
74 return z
75 case reflect.Struct:
76 if v.Type() == reflect.TypeOf(t) {
77 if v.Interface().(time.Time).IsZero() {
78 return true
79 }
80 return false
81 }
82 z := true
83 for i := 0; i < v.NumField(); i++ {
84 z = z && isZero(v.Field(i))
85 }
86 return z
87 }
88 // Compare other types directly:
89 z := reflect.Zero(v.Type())
90 return v.Interface() == z.Interface()
91}
92
Jamie Hannafordb280dea2014-10-24 15:14:06 +020093/*
Ash Wilson0735acb2014-10-31 14:18:00 -040094BuildQueryString is an internal function to be used by request methods in
95individual resource packages.
Jamie Hannafordb280dea2014-10-24 15:14:06 +020096
Ash Wilson0735acb2014-10-31 14:18:00 -040097It accepts a tagged structure and expands it into a URL struct. Field names are
98converted into query parameters based on a "q" tag. For example:
99
100 type struct Something {
Jamie Hannafordb280dea2014-10-24 15:14:06 +0200101 Bar string `q:"x_bar"`
102 Baz int `q:"lorem_ipsum"`
Jamie Hannafordb280dea2014-10-24 15:14:06 +0200103 }
104
Ash Wilson0735acb2014-10-31 14:18:00 -0400105 instance := Something{
106 Bar: "AAA",
107 Baz: "BBB",
108 }
109
110will be converted into "?x_bar=AAA&lorem_ipsum=BBB".
111
112The struct's fields may be strings, integers, or boolean values. Fields left at
Alex Gaynorc6cc18f2014-10-31 13:48:58 -0700113their type's zero value will be omitted from the query.
Jamie Hannafordb280dea2014-10-24 15:14:06 +0200114*/
Jon Perrittde47eac2014-09-30 15:34:17 -0500115func BuildQueryString(opts interface{}) (*url.URL, error) {
Jon Perrittf90a43c2014-09-28 20:09:46 -0500116 optsValue := reflect.ValueOf(opts)
117 if optsValue.Kind() == reflect.Ptr {
118 optsValue = optsValue.Elem()
119 }
120
121 optsType := reflect.TypeOf(opts)
122 if optsType.Kind() == reflect.Ptr {
123 optsType = optsType.Elem()
124 }
125
Jamie Hannafordf68c3e42014-11-18 13:02:09 +0100126 params := url.Values{}
127
Jon Perrittf90a43c2014-09-28 20:09:46 -0500128 if optsValue.Kind() == reflect.Struct {
129 for i := 0; i < optsValue.NumField(); i++ {
130 v := optsValue.Field(i)
131 f := optsType.Field(i)
132 qTag := f.Tag.Get("q")
133
134 // if the field has a 'q' tag, it goes in the query string
135 if qTag != "" {
136 tags := strings.Split(qTag, ",")
137
138 // if the field is set, add it to the slice of query pieces
139 if !isZero(v) {
140 switch v.Kind() {
141 case reflect.String:
Jamie Hannafordf68c3e42014-11-18 13:02:09 +0100142 params.Add(tags[0], v.String())
Jon Perrittf90a43c2014-09-28 20:09:46 -0500143 case reflect.Int:
Jamie Hannafordf68c3e42014-11-18 13:02:09 +0100144 params.Add(tags[0], strconv.FormatInt(v.Int(), 10))
Jon Perrittf90a43c2014-09-28 20:09:46 -0500145 case reflect.Bool:
Jamie Hannafordf68c3e42014-11-18 13:02:09 +0100146 params.Add(tags[0], strconv.FormatBool(v.Bool()))
Jon Perrittf90a43c2014-09-28 20:09:46 -0500147 }
148 } else {
149 // Otherwise, the field is not set.
150 if len(tags) == 2 && tags[1] == "required" {
151 // And the field is required. Return an error.
Jon Perrittdb00ad12014-09-30 16:29:50 -0500152 return nil, fmt.Errorf("Required query parameter [%s] not set.", f.Name)
Jon Perrittf90a43c2014-09-28 20:09:46 -0500153 }
154 }
155 }
Jamie Hannafordf68c3e42014-11-18 13:02:09 +0100156 }
Jon Perrittf90a43c2014-09-28 20:09:46 -0500157
Jamie Hannafordf68c3e42014-11-18 13:02:09 +0100158 return &url.URL{RawQuery: params.Encode()}, nil
Jon Perrittf90a43c2014-09-28 20:09:46 -0500159 }
160 // Return an error if the underlying type of 'opts' isn't a struct.
Jon Perrittde47eac2014-09-30 15:34:17 -0500161 return nil, fmt.Errorf("Options type is not a struct.")
Jon Perrittf90a43c2014-09-28 20:09:46 -0500162}
163
Ash Wilson0735acb2014-10-31 14:18:00 -0400164/*
165BuildHeaders is an internal function to be used by request methods in
166individual resource packages.
167
Alex Gaynorc6cc18f2014-10-31 13:48:58 -0700168It accepts an arbitrary tagged structure and produces a string map that's
Ash Wilson0735acb2014-10-31 14:18:00 -0400169suitable for use as the HTTP headers of an outgoing request. Field names are
170mapped to header names based in "h" tags.
171
172 type struct Something {
173 Bar string `h:"x_bar"`
174 Baz int `h:"lorem_ipsum"`
175 }
176
177 instance := Something{
178 Bar: "AAA",
179 Baz: "BBB",
180 }
181
182will be converted into:
183
184 map[string]string{
185 "x_bar": "AAA",
186 "lorem_ipsum": "BBB",
187 }
188
189Untagged fields and fields left at their zero values are skipped. Integers,
190booleans and string values are supported.
191*/
Jon Perrittf90a43c2014-09-28 20:09:46 -0500192func BuildHeaders(opts interface{}) (map[string]string, error) {
193 optsValue := reflect.ValueOf(opts)
194 if optsValue.Kind() == reflect.Ptr {
195 optsValue = optsValue.Elem()
196 }
197
198 optsType := reflect.TypeOf(opts)
199 if optsType.Kind() == reflect.Ptr {
200 optsType = optsType.Elem()
201 }
202
203 optsMap := make(map[string]string)
204 if optsValue.Kind() == reflect.Struct {
205 for i := 0; i < optsValue.NumField(); i++ {
206 v := optsValue.Field(i)
207 f := optsType.Field(i)
208 hTag := f.Tag.Get("h")
209
210 // if the field has a 'h' tag, it goes in the header
211 if hTag != "" {
212 tags := strings.Split(hTag, ",")
213
214 // if the field is set, add it to the slice of query pieces
215 if !isZero(v) {
216 switch v.Kind() {
217 case reflect.String:
218 optsMap[tags[0]] = v.String()
219 case reflect.Int:
220 optsMap[tags[0]] = strconv.FormatInt(v.Int(), 10)
221 case reflect.Bool:
222 optsMap[tags[0]] = strconv.FormatBool(v.Bool())
223 }
224 } else {
225 // Otherwise, the field is not set.
226 if len(tags) == 2 && tags[1] == "required" {
227 // And the field is required. Return an error.
228 return optsMap, fmt.Errorf("Required header not set.")
229 }
230 }
231 }
232
233 }
234 return optsMap, nil
235 }
236 // Return an error if the underlying type of 'opts' isn't a struct.
237 return optsMap, fmt.Errorf("Options type is not a struct.")
238}
Jamie Hannaford950561c2014-11-12 11:12:20 +0100239
240// IDSliceToQueryString takes a slice of elements and converts them into a query
241// string. For example, if name=foo and slice=[]int{20, 40, 60}, then the
242// result would be `?name=20&name=40&name=60'
243func IDSliceToQueryString(name string, ids []int) string {
244 str := ""
245 for k, v := range ids {
246 if k == 0 {
247 str += "?"
248 } else {
249 str += "&"
250 }
251 str += fmt.Sprintf("%s=%s", name, strconv.Itoa(v))
252 }
253 return str
254}
255
256// IntWithinRange returns TRUE if an integer falls within a defined range, and
257// FALSE if not.
258func IntWithinRange(val, min, max int) bool {
259 return val > min && val < max
260}