-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendios.go
131 lines (108 loc) · 2.55 KB
/
sendios.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
129
130
131
package sendios
import (
"fmt"
"github.com/pkg/errors"
"io"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"net/url"
"os"
"strconv"
)
type Client struct {
Config Config
HTTPClient *http.Client
DebugRequests bool
}
type Config struct {
Project int
ClientID int
ClientToken string
}
func New(projectID, clientID int, clientToken string) *Client {
return &Client{
Config: Config{
Project: projectID,
ClientID: clientID,
ClientToken: clientToken,
},
HTTPClient: &http.Client{},
}
}
func NewFromEnv() (*Client, error) {
config := os.Getenv("SENDIOS_CONFIG")
if config == "" {
return nil, nil
}
return NewFromConfig(config)
}
func NewFromConfig(config string) (*Client, error) {
values, err := url.ParseQuery(config)
if err != nil {
return nil, errors.Wrap(err, "parse config")
}
c := Client{HTTPClient: &http.Client{}}
if val, ok := values["client_id"]; ok {
c.Config.ClientID, err = strconv.Atoi(val[0])
if err != nil {
return nil, errors.Wrap(err, "parse client_id from env")
}
}
if val, ok := values["client_token"]; ok {
c.Config.ClientToken = val[0]
}
if val, ok := values["project"]; ok {
c.Config.Project, err = strconv.Atoi(val[0])
if err != nil {
return nil, errors.Wrap(err, "parse project from env")
}
}
if c.Config.ClientID < 0 || c.Config.ClientToken == "" || c.Config.Project < 0 {
return nil, nil
}
return &c, nil
}
func (c *Client) makeRequest(method, url string, reader io.Reader) (int, []byte, error) {
req, err := http.NewRequest(method, url, reader)
if err != nil {
return 0, nil, err
}
req.SetBasicAuth(strconv.Itoa(c.Config.ClientID), c.Config.ClientToken)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
if c.DebugRequests {
data, _ := httputil.DumpRequest(req, true)
fmt.Printf("Sendios request:\n%s\n", data)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return 0, nil, errors.Wrap(err, "send request")
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Println(err)
}
}()
if c.DebugRequests {
data, _ := httputil.DumpResponse(resp, true)
fmt.Printf("Sendios response:\n%s\n", data)
}
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp.StatusCode, nil, errors.Wrap(err, "read body")
}
return resp.StatusCode, data, nil
}
type Meta struct {
Status string `json:"status"`
Time int `json:"time"`
Count int `json:"count"`
}
type ErrorResponse struct {
Meta `json:"_meta"`
Data struct {
Error string `json:"error"`
} `json:"data"`
}