-
Notifications
You must be signed in to change notification settings - Fork 279
/
client.go
91 lines (75 loc) · 1.98 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
package cmd
import (
"bytes"
"fmt"
"io/ioutil"
"mime/multipart"
"net/http"
"path/filepath"
"strings"
"time"
)
//bulkClient is an HTTP client which send multiform data to bulk API
type bulkClient struct {
httpClient *http.Client
url string
}
//newBulkClient returns configured bulkClient
func newBulkClient(host, apiKey string, fallbackFormat, skipMalformed bool) *bulkClient {
url := strings.TrimRight(host, "/") + "/api/v1/events/bulk?token=" + apiKey
if fallbackFormat {
url += "&fallback=true"
}
if skipMalformed {
url += "&skip_malformed=true"
}
return &bulkClient{
httpClient: &http.Client{Timeout: 3 * time.Minute},
url: url,
}
}
//sendGzippedMultiPart sends gzipped payload as multipart POST request
//updates progress bar
//returns error if occurred
func (bc *bulkClient) sendGzippedMultiPart(fileProgressBar ProgressBar, filePath string, payload []byte) error {
body := new(bytes.Buffer)
mpw := multipart.NewWriter(body)
part, err := mpw.CreateFormFile("file", filepath.Base(filePath))
if err != nil {
return err
}
if _, err := part.Write(payload); err != nil {
return err
}
mpw.Close()
var req *http.Request
if fileProgressBar != nil && fileProgressBar.Type() != dummyType {
proxyReader := fileProgressBar.ProxyReader(body)
defer proxyReader.Close()
req, err = http.NewRequest(http.MethodPost, bc.url, proxyReader)
} else {
req, err = http.NewRequest(http.MethodPost, bc.url, bytes.NewReader(body.Bytes()))
}
if err != nil {
return err
}
req.Header.Set("Content-Type", mpw.FormDataContentType())
req.Header.Set("Content-Encoding", "gzip")
resp, err := bc.httpClient.Do(req)
if err != nil {
return err
}
var responseBody string
if resp.Body != nil {
defer resp.Body.Close()
rb, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
responseBody = string(rb)
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("Jitsu HTTP code: %d response: %s", resp.StatusCode, responseBody)
}
return nil
}