-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathapi.go
199 lines (186 loc) · 4.64 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
package audd
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
)
// API Endpoints
const (
MainAPIEndpoint string = "https://api.audd.io/"
EnterpriseAPIEndpoint string = "https://enterprise.audd.io/"
)
type Client struct {
ApiToken string
Endpoint string
Experimental bool
}
func NewClient(apiToken string) *Client {
return &Client{
ApiToken: apiToken,
Endpoint: MainAPIEndpoint,
}
}
// Sets the endpoint used
func (c *Client) SetEndpoint(APIEndpoint string) {
c.Endpoint = APIEndpoint
}
// Call this if you want to actually start sending files without completely loading them in the memory
// Can lead to unexpected issues, like if the io.Reader returns an error while uploading is in progress, it can possibly still be counted as a request
func (c *Client) UseExperimentalUploading() {
c.Experimental = true
}
// Sends a file request to the API
func (c *Client) SendFile(file io.Reader, parameters map[string]string) ([]byte, error) {
if parameters == nil {
parameters = map[string]string{}
}
parameters["api_token"] = c.ApiToken
if c.Experimental {
errCh := make(chan error, 1)
r, w := io.Pipe()
writer := multipart.NewWriter(w)
ctx, cancel := context.WithCancel(context.Background())
req, err := http.NewRequestWithContext(ctx, "POST", c.Endpoint, r)
if err != nil {
return nil, err
}
req.TransferEncoding = []string{"chunked"}
req.Header.Set("Content-Type", writer.FormDataContentType())
go func() {
var part io.Writer
part, err := writer.CreateFormFile("file", "file")
if err != nil {
errCh <- err
cancel()
return
}
_, err = io.Copy(part, file)
if err != nil {
errCh <- err
cancel()
return
}
for key, value := range parameters {
err = writer.WriteField(key, value)
if err != nil {
errCh <- err
cancel()
return
}
}
if err = writer.Close(); err != nil {
errCh <- err
cancel()
return
}
close(errCh)
if err = w.Close(); err != nil {
fmt.Println(err)
}
}()
response, err := http.DefaultClient.Do(req)
defer closeBody(response)
if err, any := <-errCh; any {
if err != nil {
return nil, err
}
}
if err != nil {
return nil, err
}
return getResponse(response)
}
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile("file", "file")
if err != nil {
return nil, err
}
_, err = io.Copy(part, file)
if err != nil {
return nil, err
}
for key, value := range parameters {
_ = writer.WriteField(key, value)
}
err = writer.Close()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", c.Endpoint, body)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", writer.FormDataContentType())
response, err := http.DefaultClient.Do(req)
defer closeBody(response)
if err != nil {
return nil, err
}
return getResponse(response)
}
// Sends a request with the URL specified
func (c *Client) SendUrl(URL string, parameters map[string]string) ([]byte, error) {
parameters["url"] = URL
return c.Send(parameters)
}
// Sends a requests to the API
func (c *Client) Send(parameters map[string]string) ([]byte, error) {
if parameters == nil {
parameters = map[string]string{}
}
parameters["api_token"] = c.ApiToken
fields := url.Values{}
for key, value := range parameters {
fields.Add(key, value)
}
response, err := http.PostForm(c.Endpoint, fields)
defer closeBody(response)
if err != nil {
return nil, err
}
return getResponse(response)
}
// Sends a request returns the result into the v
func (c *Client) SendRequest(parameters map[string]string, v interface{}) error {
result, err := c.Send(parameters)
return handleApiResponse(result, err, v)
}
// Sends a request with a file and returns the result into the v
func (c *Client) SendFileRequest(file io.Reader, parameters map[string]string, v interface{}) error {
result, err := c.SendFile(file, parameters)
return handleApiResponse(result, err, v)
}
// Sends a request with a file URL and returns the result into the v
func (c *Client) SendUrlRequest(url string, parameters map[string]string, v interface{}) error {
result, err := c.SendUrl(url, parameters)
return handleApiResponse(result, err, v)
}
func getResponse(response *http.Response) ([]byte, error) {
return ioutil.ReadAll(response.Body)
}
func closeBody(resp *http.Response) {
if resp == nil {
return
}
if resp.Body == nil {
return
}
_ = resp.Body.Close()
}
func handleApiResponse(requestResult []byte, err error, v interface{}) error {
if err != nil {
return err
}
err = json.Unmarshal(requestResult, v)
if err != nil {
return err
}
return nil
}