blob: a72aaed25187f761062aefad8f1fd3fff92d5293 [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 Hannafordcb12ee62014-10-06 15:35:36 +0200126 var optsSlice []string
Jon Perrittf90a43c2014-09-28 20:09:46 -0500127 if optsValue.Kind() == reflect.Struct {
128 for i := 0; i < optsValue.NumField(); i++ {
129 v := optsValue.Field(i)
130 f := optsType.Field(i)
131 qTag := f.Tag.Get("q")
132
133 // if the field has a 'q' tag, it goes in the query string
134 if qTag != "" {
135 tags := strings.Split(qTag, ",")
136
137 // if the field is set, add it to the slice of query pieces
138 if !isZero(v) {
139 switch v.Kind() {
140 case reflect.String:
141 optsSlice = append(optsSlice, tags[0]+"="+v.String())
142 case reflect.Int:
143 optsSlice = append(optsSlice, tags[0]+"="+strconv.FormatInt(v.Int(), 10))
144 case reflect.Bool:
145 optsSlice = append(optsSlice, tags[0]+"="+strconv.FormatBool(v.Bool()))
146 }
147 } else {
148 // Otherwise, the field is not set.
149 if len(tags) == 2 && tags[1] == "required" {
150 // And the field is required. Return an error.
Jon Perrittdb00ad12014-09-30 16:29:50 -0500151 return nil, fmt.Errorf("Required query parameter [%s] not set.", f.Name)
Jon Perrittf90a43c2014-09-28 20:09:46 -0500152 }
153 }
154 }
155
156 }
157 // URL encode the string for safety.
Jon Perritt255b6f82014-09-30 16:07:50 -0500158 s := strings.Join(optsSlice, "&")
Jon Perrittf90a43c2014-09-28 20:09:46 -0500159 if s != "" {
160 s = "?" + s
161 }
Jon Perrittde47eac2014-09-30 15:34:17 -0500162 u, err := url.Parse(s)
163 if err != nil {
164 return nil, err
165 }
166 return u, nil
Jon Perrittf90a43c2014-09-28 20:09:46 -0500167 }
168 // Return an error if the underlying type of 'opts' isn't a struct.
Jon Perrittde47eac2014-09-30 15:34:17 -0500169 return nil, fmt.Errorf("Options type is not a struct.")
Jon Perrittf90a43c2014-09-28 20:09:46 -0500170}
171
Ash Wilson0735acb2014-10-31 14:18:00 -0400172/*
173BuildHeaders is an internal function to be used by request methods in
174individual resource packages.
175
Alex Gaynorc6cc18f2014-10-31 13:48:58 -0700176It accepts an arbitrary tagged structure and produces a string map that's
Ash Wilson0735acb2014-10-31 14:18:00 -0400177suitable for use as the HTTP headers of an outgoing request. Field names are
178mapped to header names based in "h" tags.
179
180 type struct Something {
181 Bar string `h:"x_bar"`
182 Baz int `h:"lorem_ipsum"`
183 }
184
185 instance := Something{
186 Bar: "AAA",
187 Baz: "BBB",
188 }
189
190will be converted into:
191
192 map[string]string{
193 "x_bar": "AAA",
194 "lorem_ipsum": "BBB",
195 }
196
197Untagged fields and fields left at their zero values are skipped. Integers,
198booleans and string values are supported.
199*/
Jon Perrittf90a43c2014-09-28 20:09:46 -0500200func BuildHeaders(opts interface{}) (map[string]string, error) {
201 optsValue := reflect.ValueOf(opts)
202 if optsValue.Kind() == reflect.Ptr {
203 optsValue = optsValue.Elem()
204 }
205
206 optsType := reflect.TypeOf(opts)
207 if optsType.Kind() == reflect.Ptr {
208 optsType = optsType.Elem()
209 }
210
211 optsMap := make(map[string]string)
212 if optsValue.Kind() == reflect.Struct {
213 for i := 0; i < optsValue.NumField(); i++ {
214 v := optsValue.Field(i)
215 f := optsType.Field(i)
216 hTag := f.Tag.Get("h")
217
218 // if the field has a 'h' tag, it goes in the header
219 if hTag != "" {
220 tags := strings.Split(hTag, ",")
221
222 // if the field is set, add it to the slice of query pieces
223 if !isZero(v) {
224 switch v.Kind() {
225 case reflect.String:
226 optsMap[tags[0]] = v.String()
227 case reflect.Int:
228 optsMap[tags[0]] = strconv.FormatInt(v.Int(), 10)
229 case reflect.Bool:
230 optsMap[tags[0]] = strconv.FormatBool(v.Bool())
231 }
232 } else {
233 // Otherwise, the field is not set.
234 if len(tags) == 2 && tags[1] == "required" {
235 // And the field is required. Return an error.
236 return optsMap, fmt.Errorf("Required header not set.")
237 }
238 }
239 }
240
241 }
242 return optsMap, nil
243 }
244 // Return an error if the underlying type of 'opts' isn't a struct.
245 return optsMap, fmt.Errorf("Options type is not a struct.")
246}
Jamie Hannaford950561c2014-11-12 11:12:20 +0100247
248// IDSliceToQueryString takes a slice of elements and converts them into a query
249// string. For example, if name=foo and slice=[]int{20, 40, 60}, then the
250// result would be `?name=20&name=40&name=60'
251func IDSliceToQueryString(name string, ids []int) string {
252 str := ""
253 for k, v := range ids {
254 if k == 0 {
255 str += "?"
256 } else {
257 str += "&"
258 }
259 str += fmt.Sprintf("%s=%s", name, strconv.Itoa(v))
260 }
261 return str
262}
263
264// IntWithinRange returns TRUE if an integer falls within a defined range, and
265// FALSE if not.
266func IntWithinRange(val, min, max int) bool {
267 return val > min && val < max
268}