| 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 | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame^] | 9 | // WaitFor polls a predicate function once per second up to secs times to wait | 
 | 10 | // for a certain state to arrive. | 
 | 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 | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame^] | 17 | 		// Execute the function | 
| Jon Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 18 | 		satisfied, err := predicate() | 
 | 19 | 		if err != nil { | 
 | 20 | 			return err | 
 | 21 | 		} | 
 | 22 | 		if satisfied { | 
 | 23 | 			return nil | 
 | 24 | 		} | 
| Jamie Hannaford | f9b8bf5 | 2014-10-23 16:56:36 +0200 | [diff] [blame^] | 25 |  | 
 | 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 Perritt | fa2c65e | 2014-10-02 20:32:43 -0500 | [diff] [blame] | 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 | } |