forked from tw4dl/libretto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
104 lines (94 loc) · 2.52 KB
/
util.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
97
98
99
100
101
102
103
104
// Copyright 2015 Apcera Inc. All rights reserved.
package digitalocean
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
)
// BuildRequest builds an http request for this provider.
func BuildRequest(token, method, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+token)
return req, nil
}
// Update vm.Droplet values. This occurs in GetState(), so we call that and
// ignore the state string.
func (vm *VM) Update() error {
_, err := vm.GetState()
return err
}
// GetDroplet returns a single droplet
func GetDroplet(token, id string) (*Droplet, error) {
client := &http.Client{}
req, err := BuildRequest(token, "GET", apiBaseURL+apiDropletURL+"/"+id, nil)
if err != nil {
return nil, err
}
rsp, err := client.Do(req)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, err
}
if rsp.Status[0] != StatusOk {
return nil, fmt.Errorf("Error: %s: %s", rsp.Status, string(b))
}
r := &DropletResponse{}
err = json.Unmarshal(b, r)
if err != nil {
return nil, err
}
return r.Droplet, nil
}
// GetDroplets returns and array of droplets
func GetDroplets(token string) (*DropletsResponse, error) {
client := &http.Client{}
req, err := BuildRequest(token, "GET", apiBaseURL+apiDropletURL, nil)
if err != nil {
return nil, err
}
rsp, err := client.Do(req)
if err != nil {
return nil, err
}
defer rsp.Body.Close()
b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, err
}
if rsp.Status[0] != StatusOk {
return nil, fmt.Errorf("Error: %s: %s", rsp.Status, string(b))
}
r := &DropletsResponse{}
err = json.Unmarshal(b, r)
if err != nil {
return nil, err
}
return r, nil
}
// PrintDroplet prints the basic droplet values
func PrintDroplet(droplet *Droplet) {
fmt.Println("ID:", droplet.ID)
fmt.Println("Name:", droplet.Name)
fmt.Println("Status:", droplet.Status)
fmt.Println("Locked:", fmt.Sprintf("%t", droplet.Locked))
fmt.Println("CreatedAt:", droplet.CreatedAt.Format("2006-01-02 15:04:05"))
fmt.Println("SizeSlug:", droplet.Size.Slug)
fmt.Println("Region:", droplet.Region.Name)
fmt.Println("Image:", droplet.Image.Name)
for i, ip := range droplet.Networks.V4 {
fmt.Println(fmt.Sprintf("IP: %d", i+1), ip.IPAddress, ip.Type)
}
for i, ip := range droplet.Networks.V6 {
fmt.Println(fmt.Sprintf("IP: %d", i+1), ip.IPAddress, ip.Type)
}
}