forked from crewjam/awsregion
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathawsregion.go
40 lines (33 loc) · 889 Bytes
/
awsregion.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
package awsregion
import (
"io/ioutil"
"net/http"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
)
var getAvailabilityZoneOnce sync.Once
var availabilityZone string
// GuessRegion updates the AWS configuration `c` with the
// current region if one is not set by examining EC2 metadata
func GuessRegion(c *aws.Config) {
if c.Region != nil && *c.Region != "" {
return
}
getAvailabilityZoneOnce.Do(func() {
req, _ := http.NewRequest("GET",
"http://169.254.169.254/latest/meta-data/placement/availability-zone",
nil)
httpClient := *http.DefaultClient
httpClient.Timeout = time.Second
resp, err := httpClient.Do(req)
if err != nil || resp.StatusCode != http.StatusOK {
return
}
body, _ := ioutil.ReadAll(resp.Body)
availabilityZone = string(body)
})
if availabilityZone != "" {
c.Region = aws.String(availabilityZone[:len(availabilityZone)-1])
}
}