Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 1 | package gophercloud |
| 2 | |
| 3 | import ( |
Jamie Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame] | 4 | "errors" |
Ash Wilson | a844064 | 2014-10-07 09:55:58 -0400 | [diff] [blame] | 5 | "strings" |
Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 6 | "time" |
| 7 | ) |
| 8 | |
Jamie Hannaford | b280dea | 2014-10-24 15:14:06 +0200 | [diff] [blame^] | 9 | // WaitFor polls a predicate function, once per second, up to a timeout limit. |
| 10 | // It usually does this to wait for the resource to transition to a certain state. |
Jamie Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame] | 11 | func WaitFor(timeout int, predicate func() (bool, error)) error { |
| 12 | start := time.Now().Second() |
| 13 | for { |
| 14 | // Force a 1s sleep |
Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 15 | time.Sleep(1 * time.Second) |
| 16 | |
Jamie Hannaford | 3ac3aa7 | 2014-10-23 17:30:49 +0200 | [diff] [blame] | 17 | // If a timeout is set, and that's been exceeded, shut it down |
| 18 | if timeout >= 0 && time.Now().Second()-start >= timeout { |
| 19 | return errors.New("A timeout occurred") |
| 20 | } |
| 21 | |
Jamie Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame] | 22 | // Execute the function |
Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 23 | satisfied, err := predicate() |
| 24 | if err != nil { |
| 25 | return err |
| 26 | } |
| 27 | if satisfied { |
| 28 | return nil |
| 29 | } |
| 30 | } |
Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 31 | } |
Ash Wilson | a844064 | 2014-10-07 09:55:58 -0400 | [diff] [blame] | 32 | |
| 33 | // NormalizeURL ensures that each endpoint URL has a closing `/`, as expected by ServiceClient. |
| 34 | func NormalizeURL(url string) string { |
| 35 | if !strings.HasSuffix(url, "/") { |
| 36 | return url + "/" |
| 37 | } |
| 38 | return url |
| 39 | } |
Jamie Hannaford | ee049ec | 2014-10-22 17:02:55 +0200 | [diff] [blame] | 40 | |
| 41 | // BuildQuery constructs the query section of a URI from a map. |
| 42 | func 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 | } |