/
client.go
104 lines (87 loc) · 1.99 KB
/
client.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
package main
import (
"bytes"
"encoding/json"
"log"
"mime/multipart"
"net/http"
"net/url"
"path/filepath"
)
var (
apiEndpoint = "https://voip.ms/api/v1/rest.php"
confFileName = "config.toml"
)
type client struct {
url string
credentials
}
func newClient() *client {
c := readCredentials()
return &client{url: apiEndpoint, credentials: c}
}
func readCredentials() credentials {
confDir, err := getDefaultConfigDir()
if err != nil {
log.Fatal(err)
}
conf, err := loadConfig(filepath.Join(confDir, confFileName))
if err != nil {
log.Fatal(err)
}
return conf.Credentials
}
func (c *client) doRequest(req *http.Request, respStruct interface{}) {
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body := resp.Body
dec := json.NewDecoder(body)
if err := dec.Decode(respStruct); err != nil {
log.Fatal(err)
}
return
}
func (c *client) getRequest(method string, values url.Values, respStruct interface{}) {
u, err := url.Parse(c.url)
if err != nil {
log.Fatal(err)
}
values.Add("api_username", c.Email)
values.Add("api_password", c.Password)
values.Add("method", method)
u.RawQuery = values.Encode()
req, err := http.NewRequest("GET", u.String(), nil)
req.Header.Set("Content-Type", "application/json")
if err != nil {
log.Fatal(err)
}
c.doRequest(req, respStruct)
return
}
func (c *client) postRequest(method string, p postParams, respStruct interface{}) {
bodyBuf := &bytes.Buffer{}
bodyWriter := multipart.NewWriter(bodyBuf)
bodyWriter.WriteField("api_username", c.Email)
bodyWriter.WriteField("api_password", c.Password)
bodyWriter.WriteField("method", method)
for k, v := range p {
bodyWriter.WriteField(k, v)
}
contentType := bodyWriter.FormDataContentType()
bodyWriter.Close()
/*
*fmt.Println(bodyBuf)
*return
*/
req, err := http.NewRequest("POST", c.url, bodyBuf)
req.Header.Set("Content-Type", contentType)
if err != nil {
log.Fatal(err)
}
c.doRequest(req, respStruct)
return
}