-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsendcloud.go
114 lines (100 loc) · 2.33 KB
/
sendcloud.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
package sendcloud
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
)
type Payload interface {
GetPayload() interface{}
}
type Response interface {
GetResponse() interface{}
SetResponse(body []byte) error
}
type ErrorResponse struct {
Error struct {
Code int `json:"code"`
Request string `json:"request"`
Message string `json:"message"`
} `json:"error"`
}
type Error struct {
Code int `json:"code"`
Request string `json:"request"`
Message string `json:"message"`
}
func (e *Error) Error() string {
return fmt.Sprintf("request %s resulted in error code %d: %s", e.Request, e.Code, e.Message)
}
// Send a request to Sendcloud with given method, path, payload and credentials
func Request(method string, uri string, payload Payload, apiKey string, apiSecret string, r Response) error {
client := http.Client{
Timeout: 30 * time.Second,
}
var request *http.Request
var err error
if payload == nil {
request, err = http.NewRequest(method, getUrl(uri), nil)
if err != nil {
return err
}
} else {
body, err := json.Marshal(payload.GetPayload())
if err != nil {
return err
}
request, err = http.NewRequest(method, getUrl(uri), bytes.NewBuffer(body))
if err != nil {
return err
}
}
if payload != nil {
request.Header.Set("Content-Type", "application/json")
}
request.Header.Set("User-Agent", "Sendcloud-Go/0.1 ("+apiKey+")")
request.SetBasicAuth(apiKey, apiSecret)
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
body, err := io.ReadAll(response.Body)
if err != nil {
return err
}
if response.StatusCode > 299 || response.StatusCode < 200 {
if !strings.Contains(response.Header.Get("content-type"), "application/json") {
return &Error{
Code: response.StatusCode,
Message: string(body),
}
}
// Return error response
errResponse := ErrorResponse{}
err = json.Unmarshal(body, &errResponse)
if err != nil {
return err
}
return &Error{
Code: response.StatusCode,
Request: errResponse.Error.Request,
Message: errResponse.Error.Message,
}
}
err = r.SetResponse(body)
return err
}
// Return the full URL
func getUrl(uri string) string {
var url string
if strings.HasPrefix(uri, "https://") {
url = uri
} else {
url = "https://panel.sendcloud.sc" + uri
}
return url
}