params.go 12.7 KB
Newer Older
1 2
package gophercloud

3
import (
4
	"encoding/json"
5 6 7 8 9 10 11 12
	"fmt"
	"net/url"
	"reflect"
	"strconv"
	"strings"
	"time"
)

13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
BuildRequestBody builds a map[string]interface from the given `struct`. If
parent is not an empty string, the final map[string]interface returned will
encapsulate the built one. For example:

  disk := 1
  createOpts := flavors.CreateOpts{
    ID:         "1",
    Name:       "m1.tiny",
    Disk:       &disk,
    RAM:        512,
    VCPUs:      1,
    RxTxFactor: 1.0,
  }

  body, err := gophercloud.BuildRequestBody(createOpts, "flavor")

The above example can be run as-is, however it is recommended to look at how
BuildRequestBody is used within Gophercloud to more fully understand how it
fits within the request process as a whole rather than use it directly as shown
above.
*/
Jon Perritt's avatar
Jon Perritt committed
35
func BuildRequestBody(opts interface{}, parent string) (map[string]interface{}, error) {
36 37 38 39 40 41 42 43 44 45 46 47
	optsValue := reflect.ValueOf(opts)
	if optsValue.Kind() == reflect.Ptr {
		optsValue = optsValue.Elem()
	}

	optsType := reflect.TypeOf(opts)
	if optsType.Kind() == reflect.Ptr {
		optsType = optsType.Elem()
	}

	optsMap := make(map[string]interface{})
	if optsValue.Kind() == reflect.Struct {
Jon Perritt's avatar
Jon Perritt committed
48
		//fmt.Printf("optsValue.Kind() is a reflect.Struct: %+v\n", optsValue.Kind())
49 50 51 52
		for i := 0; i < optsValue.NumField(); i++ {
			v := optsValue.Field(i)
			f := optsType.Field(i)

Jon Perritt's avatar
Jon Perritt committed
53
			if f.Name != strings.Title(f.Name) {
54
				//fmt.Printf("Skipping field: %s...\n", f.Name)
Jon Perritt's avatar
Jon Perritt committed
55 56 57
				continue
			}

58
			//fmt.Printf("Starting on field: %s...\n", f.Name)
Jon Perritt's avatar
Jon Perritt committed
59 60

			zero := isZero(v)
61
			//fmt.Printf("v is zero?: %v\n", zero)
Jon Perritt's avatar
Jon Perritt committed
62 63 64

			// if the field has a required tag that's set to "true"
			if requiredTag := f.Tag.Get("required"); requiredTag == "true" {
Jon Perritt's avatar
Jon Perritt committed
65
				//fmt.Printf("Checking required field [%s]:\n\tv: %+v\n\tisZero:%v\n", f.Name, v.Interface(), zero)
Jon Perritt's avatar
Jon Perritt committed
66 67 68 69 70 71 72 73 74 75
				// if the field's value is zero, return a missing-argument error
				if zero {
					// if the field has a 'required' tag, it can't have a zero-value
					err := ErrMissingInput{}
					err.Argument = f.Name
					return nil, err
				}
			}

			if xorTag := f.Tag.Get("xor"); xorTag != "" {
Jon Perritt's avatar
Jon Perritt committed
76
				//fmt.Printf("Checking `xor` tag for field [%s] with value %+v:\n\txorTag: %s\n", f.Name, v, xorTag)
Jon Perritt's avatar
Jon Perritt committed
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
				xorField := optsValue.FieldByName(xorTag)
				var xorFieldIsZero bool
				if reflect.ValueOf(xorField.Interface()) == reflect.Zero(xorField.Type()) {
					xorFieldIsZero = true
				} else {
					if xorField.Kind() == reflect.Ptr {
						xorField = xorField.Elem()
					}
					xorFieldIsZero = isZero(xorField)
				}
				if !(zero != xorFieldIsZero) {
					err := ErrMissingInput{}
					err.Argument = fmt.Sprintf("%s/%s", f.Name, xorTag)
					err.Info = fmt.Sprintf("Exactly one of %s and %s must be provided", f.Name, xorTag)
					return nil, err
				}
			}

			if orTag := f.Tag.Get("or"); orTag != "" {
Jon Perritt's avatar
Jon Perritt committed
96 97
				//fmt.Printf("Checking `or` tag for field with:\n\tname: %+v\n\torTag:%s\n", f.Name, orTag)
				//fmt.Printf("field is zero?: %v\n", zero)
Jon Perritt's avatar
Jon Perritt committed
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
				if zero {
					orField := optsValue.FieldByName(orTag)
					var orFieldIsZero bool
					if reflect.ValueOf(orField.Interface()) == reflect.Zero(orField.Type()) {
						orFieldIsZero = true
					} else {
						if orField.Kind() == reflect.Ptr {
							orField = orField.Elem()
						}
						orFieldIsZero = isZero(orField)
					}
					if orFieldIsZero {
						err := ErrMissingInput{}
						err.Argument = fmt.Sprintf("%s/%s", f.Name, orTag)
						err.Info = fmt.Sprintf("At least one of %s and %s must be provided", f.Name, orTag)
						return nil, err
					}
				}
			}

118 119 120 121 122
			jsonTag := f.Tag.Get("json")
			if jsonTag == "-" {
				continue
			}

Jon Perritt's avatar
Jon Perritt committed
123 124
			if v.Kind() == reflect.Struct || (v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct) {
				if zero {
Jon Perritt's avatar
Jon Perritt committed
125
					//fmt.Printf("value before change: %+v\n", optsValue.Field(i))
126
					if jsonTag != "" {
Jon Perritt's avatar
Jon Perritt committed
127 128 129 130 131 132 133 134
						jsonTagPieces := strings.Split(jsonTag, ",")
						if len(jsonTagPieces) > 1 && jsonTagPieces[1] == "omitempty" {
							if v.CanSet() {
								if !v.IsNil() {
									if v.Kind() == reflect.Ptr {
										v.Set(reflect.Zero(v.Type()))
									}
								}
Jon Perritt's avatar
Jon Perritt committed
135
								//fmt.Printf("value after change: %+v\n", optsValue.Field(i))
Jon Perritt's avatar
Jon Perritt committed
136 137 138 139 140 141
							}
						}
					}
					continue
				}

Jon Perritt's avatar
Jon Perritt committed
142
				//fmt.Printf("Calling BuildRequestBody with:\n\tv: %+v\n\tf.Name:%s\n", v.Interface(), f.Name)
Jon Perritt's avatar
Jon Perritt committed
143 144 145 146
				_, err := BuildRequestBody(v.Interface(), f.Name)
				if err != nil {
					return nil, err
				}
147 148 149
			}
		}

Jon Perritt's avatar
Jon Perritt committed
150
		//fmt.Printf("opts: %+v \n", opts)
Jon Perritt's avatar
Jon Perritt committed
151

152 153 154 155 156
		b, err := json.Marshal(opts)
		if err != nil {
			return nil, err
		}

Jon Perritt's avatar
Jon Perritt committed
157
		//fmt.Printf("string(b): %s\n", string(b))
Jon Perritt's avatar
Jon Perritt committed
158

159 160 161 162 163
		err = json.Unmarshal(b, &optsMap)
		if err != nil {
			return nil, err
		}

Jon Perritt's avatar
Jon Perritt committed
164 165 166 167 168 169
		//fmt.Printf("optsMap: %+v\n", optsMap)

		if parent != "" {
			optsMap = map[string]interface{}{parent: optsMap}
		}
		//fmt.Printf("optsMap after parent added: %+v\n", optsMap)
170 171 172 173
		return optsMap, nil
	}
	// Return an error if the underlying type of 'opts' isn't a struct.
	return nil, fmt.Errorf("Options type is not a struct.")
174 175
}

176 177 178 179 180 181 182 183 184 185 186 187 188 189
// EnabledState is a convenience type, mostly used in Create and Update
// operations. Because the zero value of a bool is FALSE, we need to use a
// pointer instead to indicate zero-ness.
type EnabledState *bool

// Convenience vars for EnabledState values.
var (
	iTrue  = true
	iFalse = false

	Enabled  EnabledState = &iTrue
	Disabled EnabledState = &iFalse
)

190 191 192 193 194 195 196 197 198 199 200
// IPVersion is a type for the possible IP address versions. Valid instances
// are IPv4 and IPv6
type IPVersion int

const (
	// IPv4 is used for IP version 4 addresses
	IPv4 IPVersion = 4
	// IPv6 is used for IP version 6 addresses
	IPv6 IPVersion = 6
)

Jamie Hannaford's avatar
Jamie Hannaford committed
201 202 203 204 205 206
// IntToPointer is a function for converting integers into integer pointers.
// This is useful when passing in options to operations.
func IntToPointer(i int) *int {
	return &i
}

207 208 209 210 211 212
/*
MaybeString is an internal function to be used by request methods in individual
resource packages.

It takes a string that might be a zero value and returns either a pointer to its
address or nil. This is useful for allowing users to conveniently omit values
213 214
from an options struct by leaving them zeroed, but still pass nil to the JSON
serializer so they'll be omitted from the request body.
215
*/
216 217 218 219 220 221
func MaybeString(original string) *string {
	if original != "" {
		return &original
	}
	return nil
}
222

223 224 225 226
/*
MaybeInt is an internal function to be used by request methods in individual
resource packages.

227 228 229
Like MaybeString, it accepts an int that may or may not be a zero value, and
returns either a pointer to its address or nil. It's intended to hint that the
JSON serializer should omit its field.
230
*/
231 232 233 234 235 236 237
func MaybeInt(original int) *int {
	if original != 0 {
		return &original
	}
	return nil
}

Jon Perritt's avatar
Jon Perritt committed
238 239 240 241 242 243 244 245 246 247 248
/*
func isUnderlyingStructZero(v reflect.Value) bool {
	switch v.Kind() {
	case reflect.Ptr:
		return isUnderlyingStructZero(v.Elem())
	default:
		return isZero(v)
	}
}
*/

249 250 251
var t time.Time

func isZero(v reflect.Value) bool {
252
	//fmt.Printf("\n\nchecking isZero for value: %+v\n", v)
253
	switch v.Kind() {
Jon Perritt's avatar
Jon Perritt committed
254 255 256 257
	case reflect.Ptr:
		if v.IsNil() {
			return true
		}
258
		return false
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
	case reflect.Func, reflect.Map, reflect.Slice:
		return v.IsNil()
	case reflect.Array:
		z := true
		for i := 0; i < v.Len(); i++ {
			z = z && isZero(v.Index(i))
		}
		return z
	case reflect.Struct:
		if v.Type() == reflect.TypeOf(t) {
			if v.Interface().(time.Time).IsZero() {
				return true
			}
			return false
		}
		z := true
		for i := 0; i < v.NumField(); i++ {
			z = z && isZero(v.Field(i))
		}
		return z
	}
	// Compare other types directly:
	z := reflect.Zero(v.Type())
282
	//fmt.Printf("zero type for value: %+v\n\n\n", z)
283 284 285
	return v.Interface() == z.Interface()
}

286
/*
287 288 289 290 291
BuildQueryString is an internal function to be used by request methods in
individual resource packages.

It accepts a tagged structure and expands it into a URL struct. Field names are
converted into query parameters based on a "q" tag. For example:
292

293
	type struct Something {
294 295 296 297
	   Bar string `q:"x_bar"`
	   Baz int    `q:"lorem_ipsum"`
	}

298 299 300 301 302 303 304 305
	instance := Something{
	   Bar: "AAA",
	   Baz: "BBB",
	}

will be converted into "?x_bar=AAA&lorem_ipsum=BBB".

The struct's fields may be strings, integers, or boolean values. Fields left at
Alex Gaynor's avatar
Alex Gaynor committed
306
their type's zero value will be omitted from the query.
307
*/
308
func BuildQueryString(opts interface{}) (*url.URL, error) {
309 310 311 312 313 314 315 316 317 318
	optsValue := reflect.ValueOf(opts)
	if optsValue.Kind() == reflect.Ptr {
		optsValue = optsValue.Elem()
	}

	optsType := reflect.TypeOf(opts)
	if optsType.Kind() == reflect.Ptr {
		optsType = optsType.Elem()
	}

319 320
	params := url.Values{}

321 322 323 324 325 326 327 328 329 330 331 332
	if optsValue.Kind() == reflect.Struct {
		for i := 0; i < optsValue.NumField(); i++ {
			v := optsValue.Field(i)
			f := optsType.Field(i)
			qTag := f.Tag.Get("q")

			// if the field has a 'q' tag, it goes in the query string
			if qTag != "" {
				tags := strings.Split(qTag, ",")

				// if the field is set, add it to the slice of query pieces
				if !isZero(v) {
333
				loop:
334
					switch v.Kind() {
335 336 337
					case reflect.Ptr:
						v = v.Elem()
						goto loop
338
					case reflect.String:
339
						params.Add(tags[0], v.String())
340
					case reflect.Int:
341
						params.Add(tags[0], strconv.FormatInt(v.Int(), 10))
342
					case reflect.Bool:
343
						params.Add(tags[0], strconv.FormatBool(v.Bool()))
344
					case reflect.Slice:
345 346 347 348 349 350
						switch v.Type().Elem() {
						case reflect.TypeOf(0):
							for i := 0; i < v.Len(); i++ {
								params.Add(tags[0], strconv.FormatInt(v.Index(i).Int(), 10))
							}
						default:
351 352 353 354
							for i := 0; i < v.Len(); i++ {
								params.Add(tags[0], v.Index(i).String())
							}
						}
355 356 357 358 359 360 361 362 363
					case reflect.Map:
						if v.Type().Key().Kind() == reflect.String && v.Type().Elem().Kind() == reflect.String {
							var s []string
							for _, k := range v.MapKeys() {
								value := v.MapIndex(k).String()
								s = append(s, fmt.Sprintf("'%s':'%s'", k.String(), value))
							}
							params.Add(tags[0], fmt.Sprintf("{%s}", strings.Join(s, ", ")))
						}
364 365
					}
				} else {
366 367
					// if the field has a 'required' tag, it can't have a zero-value
					if requiredTag := f.Tag.Get("required"); requiredTag == "true" {
368
						return &url.URL{}, fmt.Errorf("Required query parameter [%s] not set.", f.Name)
369 370 371 372
					}
				}
			}
		}
373 374

		return &url.URL{RawQuery: params.Encode()}, nil
375 376
	}
	// Return an error if the underlying type of 'opts' isn't a struct.
377
	return nil, fmt.Errorf("Options type is not a struct.")
378 379
}

380 381 382 383
/*
BuildHeaders is an internal function to be used by request methods in
individual resource packages.

Alex Gaynor's avatar
Alex Gaynor committed
384
It accepts an arbitrary tagged structure and produces a string map that's
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
suitable for use as the HTTP headers of an outgoing request. Field names are
mapped to header names based in "h" tags.

  type struct Something {
    Bar string `h:"x_bar"`
    Baz int    `h:"lorem_ipsum"`
  }

  instance := Something{
    Bar: "AAA",
    Baz: "BBB",
  }

will be converted into:

  map[string]string{
    "x_bar": "AAA",
    "lorem_ipsum": "BBB",
  }

Untagged fields and fields left at their zero values are skipped. Integers,
booleans and string values are supported.
*/
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
func BuildHeaders(opts interface{}) (map[string]string, error) {
	optsValue := reflect.ValueOf(opts)
	if optsValue.Kind() == reflect.Ptr {
		optsValue = optsValue.Elem()
	}

	optsType := reflect.TypeOf(opts)
	if optsType.Kind() == reflect.Ptr {
		optsType = optsType.Elem()
	}

	optsMap := make(map[string]string)
	if optsValue.Kind() == reflect.Struct {
		for i := 0; i < optsValue.NumField(); i++ {
			v := optsValue.Field(i)
			f := optsType.Field(i)
			hTag := f.Tag.Get("h")

			// if the field has a 'h' tag, it goes in the header
			if hTag != "" {
				tags := strings.Split(hTag, ",")

				// if the field is set, add it to the slice of query pieces
				if !isZero(v) {
					switch v.Kind() {
					case reflect.String:
						optsMap[tags[0]] = v.String()
					case reflect.Int:
						optsMap[tags[0]] = strconv.FormatInt(v.Int(), 10)
					case reflect.Bool:
						optsMap[tags[0]] = strconv.FormatBool(v.Bool())
					}
				} else {
441 442 443
					// if the field has a 'required' tag, it can't have a zero-value
					if requiredTag := f.Tag.Get("required"); requiredTag == "true" {
						return optsMap, fmt.Errorf("Required header [%s] not set.", f.Name)
444 445 446 447 448 449 450 451 452 453
					}
				}
			}

		}
		return optsMap, nil
	}
	// Return an error if the underlying type of 'opts' isn't a struct.
	return optsMap, fmt.Errorf("Options type is not a struct.")
}
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475

// IDSliceToQueryString takes a slice of elements and converts them into a query
// string. For example, if name=foo and slice=[]int{20, 40, 60}, then the
// result would be `?name=20&name=40&name=60'
func IDSliceToQueryString(name string, ids []int) string {
	str := ""
	for k, v := range ids {
		if k == 0 {
			str += "?"
		} else {
			str += "&"
		}
		str += fmt.Sprintf("%s=%s", name, strconv.Itoa(v))
	}
	return str
}

// IntWithinRange returns TRUE if an integer falls within a defined range, and
// FALSE if not.
func IntWithinRange(val, min, max int) bool {
	return val > min && val < max
}