forked from civo/civogo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathregion.go
96 lines (82 loc) · 2.31 KB
/
region.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package civogo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"strings"
)
// Region represents a geographical/DC region for Civo resources
type Region struct {
Code string `json:"code"`
Name string `json:"name"`
Type string `json:"type"`
OutOfCapacity bool `json:"out_of_capacity"`
Country string `json:"country"`
CountryName string `json:"country_name"`
Features Feature `json:"features"`
Default bool `json:"default"`
}
// Feature represent a all feature inside a region
type Feature struct {
Iaas bool `json:"iaas"`
Kubernetes bool `json:"kubernetes"`
}
// ListRegions returns all load balancers owned by the calling API account
func (c *Client) ListRegions() ([]Region, error) {
resp, err := c.SendGetRequest("/v2/regions")
if err != nil {
return nil, decodeERROR(err)
}
regions := make([]Region, 0)
if err := json.NewDecoder(bytes.NewReader(resp)).Decode(®ions); err != nil {
return nil, err
}
return regions, nil
}
// FindRegion is a function to find a region
func (c *Client) FindRegion(search string) (*Region, error) {
allregion, err := c.ListRegions()
if err != nil {
return nil, decodeERROR(err)
}
exactMatch := false
partialMatchesCount := 0
result := Region{}
search = strings.ToUpper(search)
for _, value := range allregion {
name := strings.ToUpper(value.Name)
code := strings.ToUpper(value.Code)
if name == search || code == search {
exactMatch = true
result = value
} else if strings.Contains(name, search) || strings.Contains(code, search) {
if !exactMatch {
result = value
partialMatchesCount++
}
}
}
if exactMatch || partialMatchesCount == 1 {
return &result, nil
} else if partialMatchesCount > 1 {
err := fmt.Errorf("unable to find %s because there were multiple matches", search)
return nil, MultipleMatchesError.wrap(err)
} else {
err := fmt.Errorf("unable to find %s, zero matches", search)
return nil, ZeroMatchesError.wrap(err)
}
}
// GetDefaultRegion finds the default region for an account
func (c *Client) GetDefaultRegion() (*Region, error) {
allregion, err := c.ListRegions()
if err != nil {
return nil, decodeERROR(err)
}
for _, region := range allregion {
if region.Default {
return ®ion, nil
}
}
return nil, errors.New("no default region found")
}