-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
128 lines (105 loc) · 2.63 KB
/
api.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package vmmanagerapi
import (
"bytes"
"crypto/tls"
"fmt"
"io"
"net/http"
)
const (
ApiVersion = "v3"
AuthApiV4 = "v4"
DefaultService = "vm"
AuthService = "auth"
AuthByEmailAndPasswordUri = "/public/auth"
AuthByKeyUri = "/public/auth_by_key"
AuthV4Uri = "/public/token"
requestTypePost = "POST"
requestTypeGet = "GET"
requestTypeDelete = "DELETE"
BackupUri = "/backup"
DiskUri = "/disk"
HostUri = "/host"
ClusterUri = "/cluster"
SSHUri = "/ssh_key"
)
var (
NilPayload = []byte("")
)
type Api struct {
Host string
conn *http.Client
AuthData AuthData
}
type ParamsQuery struct {
Query string
}
type Error struct {
Code int `json:"code,omitempty"`
Msg string `json:"msg,omitempty"`
}
//New Api
func New(host string) *Api {
return &Api{
Host: host,
conn: connect(),
}
}
func (a *Api) entrypoint(service string) string {
switch service {
case AuthService:
return fmt.Sprintf("https://%s/%s/%s", a.Host, AuthService, AuthApiV4)
default:
return fmt.Sprintf("https://%s/%s/%s", a.Host, DefaultService, ApiVersion)
}
}
func connect() *http.Client {
tl := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
}
return &http.Client{Transport: tl}
}
// NewRequest make requests to API.
// payload: marshaled json object, uri: endpoit uri, reqType: POST/GET/DELETE, service vm/auth
func (a *Api) NewRequest(payload []byte, uri string, reqType string, service string) ([]byte, error) {
body := bytes.NewReader(payload)
req, err := http.NewRequest(reqType, a.entrypoint(service)+uri, body)
if err != nil {
return nil, err
}
req = a.SetHeaders(req)
resp, err := a.conn.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
bodyResp, err := io.ReadAll(resp.Body)
return bodyResp, err
}
// SetHeaders set default headers for API requests
func (a *Api) SetHeaders(req *http.Request) *http.Request {
req.Proto = "HTTP/2"
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
if a.AuthData.Token != "" {
req.Header.Set("X-XSRF-TOKEN", a.AuthData.Token)
}
return req
}
// Make query returns ?x=y&z=t
func MakeQuery(params map[string]string) *ParamsQuery {
query := "?"
for k, v := range params {
query += fmt.Sprintf("%s=%s&", k, v)
}
if query[len(query)-1:] == "&" {
query = query[:len(query)-1]
}
return &ParamsQuery{Query: query}
}
//NilQuery return nil query
func NilQuery() *ParamsQuery {
return &ParamsQuery{}
}