forked from vultr/govultr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
os.go
84 lines (68 loc) · 1.82 KB
/
os.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
package govultr
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strconv"
)
// OSService is the interface to interact with the operating system endpoint on the Vultr API
// Link: https://www.vultr.com/api/#os
type OSService interface {
List(ctx context.Context) ([]OS, error)
}
// OSServiceHandler handles interaction with the operating system methods for the Vultr API
type OSServiceHandler struct {
client *Client
}
// OS represents a Vultr operating system
type OS struct {
OsID int `json:"OSID"`
Name string `json:"name"`
Arch string `json:"arch"`
Family string `json:"family"`
Windows bool `json:"windows"`
}
// UnmarshalJSON implements json.Unmarshaller on OS to handle the inconsistent types returned from the Vultr API.
func (o *OS) UnmarshalJSON(data []byte) (err error) {
if o == nil {
*o = OS{}
}
var v map[string]interface{}
if err := json.Unmarshal(data, &v); err != nil {
return err
}
i, err := strconv.Atoi(fmt.Sprintf("%v", v["OSID"]))
if err != nil {
return err
}
o.OsID = i
value := fmt.Sprintf("%v", v["windows"])
o.Windows = false
if value == "true" {
o.Windows = true
}
o.Name = fmt.Sprintf("%v", v["name"])
o.Arch = fmt.Sprintf("%v", v["arch"])
o.Family = fmt.Sprintf("%v", v["family"])
return nil
}
// List retrieves a list of available operating systems.
// If the Windows flag is true, a Windows license will be included with the instance, which will increase the cost.
func (o *OSServiceHandler) List(ctx context.Context) ([]OS, error) {
uri := "/v1/os/list"
req, err := o.client.NewRequest(ctx, http.MethodGet, uri, nil)
if err != nil {
return nil, err
}
osMap := make(map[string]OS)
err = o.client.DoWithContext(ctx, req, &osMap)
if err != nil {
return nil, err
}
var oses []OS
for _, os := range osMap {
oses = append(oses, os)
}
return oses, nil
}