-
Notifications
You must be signed in to change notification settings - Fork 8
/
regions.go
69 lines (56 loc) · 1.45 KB
/
regions.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
package scalingo
import (
"context"
"sync"
"gopkg.in/errgo.v1"
"github.com/Scalingo/go-scalingo/v7/http"
)
var (
ErrRegionNotFound = errgo.New("Region not found")
regionCache = map[string]Region{}
regionCacheMutex = &sync.Mutex{}
)
type RegionsService interface {
RegionsList(context.Context) ([]Region, error)
}
type Region struct {
Name string `json:"name"`
DisplayName string `json:"display_name"`
SSH string `json:"ssh"`
API string `json:"api"`
Dashboard string `json:"dashboard"`
DatabaseAPI string `json:"database_api"`
Default bool `json:"default"`
}
type regionsRes struct {
Regions []Region `json:"regions"`
}
func (c *Client) RegionsList(ctx context.Context) ([]Region, error) {
var res regionsRes
err := c.AuthAPI().DoRequest(ctx, &http.APIRequest{
Method: "GET",
Endpoint: "/regions",
}, &res)
if err != nil {
return nil, errgo.Notef(err, "fail to call GET /regions")
}
return res.Regions, nil
}
func (c *Client) getRegion(ctx context.Context, regionName string) (Region, error) {
regionCacheMutex.Lock()
defer regionCacheMutex.Unlock()
if _, ok := regionCache[regionName]; !ok {
regions, err := c.RegionsList(ctx)
if err != nil {
return Region{}, errgo.Notef(err, "fail to list regions")
}
for _, region := range regions {
regionCache[region.Name] = region
}
}
region, ok := regionCache[regionName]
if !ok {
return Region{}, ErrRegionNotFound
}
return region, nil
}