blob: 92ca910ff38363cff0c411458cddf921e3f0ea49 [file] [log] [blame]
Jon Perrittfa2c65e2014-10-02 20:32:43 -05001package gophercloud
2
3import (
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +02004 "errors"
Ash Wilsona8440642014-10-07 09:55:58 -04005 "strings"
Jon Perrittfa2c65e2014-10-02 20:32:43 -05006 "time"
7)
8
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +02009// WaitFor polls a predicate function once per second up to secs times to wait
10// for a certain state to arrive.
11func WaitFor(timeout int, predicate func() (bool, error)) error {
12 start := time.Now().Second()
13 for {
14 // Force a 1s sleep
Jon Perrittfa2c65e2014-10-02 20:32:43 -050015 time.Sleep(1 * time.Second)
16
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +020017 // Execute the function
Jon Perrittfa2c65e2014-10-02 20:32:43 -050018 satisfied, err := predicate()
19 if err != nil {
20 return err
21 }
22 if satisfied {
23 return nil
24 }
Jamie Hannafordf9b8bf52014-10-23 16:56:36 +020025
26 // If a timeout is set, and that's been exceeded, shut it down
27 if timeout > 0 && time.Now().Second()-start >= timeout {
28 return errors.New("A timeout occurred")
29 }
Jon Perrittfa2c65e2014-10-02 20:32:43 -050030 }
Jon Perrittfa2c65e2014-10-02 20:32:43 -050031}
Ash Wilsona8440642014-10-07 09:55:58 -040032
33// NormalizeURL ensures that each endpoint URL has a closing `/`, as expected by ServiceClient.
34func NormalizeURL(url string) string {
35 if !strings.HasSuffix(url, "/") {
36 return url + "/"
37 }
38 return url
39}
Jamie Hannafordee049ec2014-10-22 17:02:55 +020040
41// BuildQuery constructs the query section of a URI from a map.
42func BuildQuery(params map[string]string) string {
43 if len(params) == 0 {
44 return ""
45 }
46
47 query := "?"
48 for k, v := range params {
49 query += k + "=" + v + "&"
50 }
51 query = query[:len(query)-1]
52 return query
53}