forked from RichardKnop/go-mailchimp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbatch.go
64 lines (54 loc) · 1.14 KB
/
batch.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
package mailchimp
import (
"encoding/json"
"io/ioutil"
)
type BatchOperation struct {
Method string `json:"method"`
Path string `json:"path"`
Body interface{} `json:"body"`
}
type Batch struct {
Operations []BatchOperation
}
func CreateBatch() Batch {
return Batch{
Operations: make([]BatchOperation, 0),
}
}
func (b *Batch) AddOperation(o BatchOperation) {
b.Operations = append(b.Operations, o)
}
func (c *Client) CreateBatch(batch *Batch) (*BatchResponse, error) {
operations, err := json.Marshal(batch)
if err != nil {
return nil, err
}
data := make(map[string]interface{})
data["operations"] = operations
resp, err := c.do(
"POST",
"/batches",
&data,
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if resp.StatusCode/100 == 2 {
batchResponse := new(BatchResponse)
if err := json.Unmarshal(responseBody, batchResponse); err != nil {
return nil, err
}
return batchResponse, nil
}
errorResponse, err := extractError(responseBody)
if err != nil {
return nil, err
}
return nil, errorResponse
}