forked from RichardKnop/go-mailchimp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
update_subscription.go
54 lines (48 loc) · 1.15 KB
/
update_subscription.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
package mailchimp
import (
"crypto/md5"
"encoding/json"
"fmt"
"io/ioutil"
"github.com/RichardKnop/go-mailchimp/status"
)
// UpdateSubscription ...
func (c *Client) UpdateSubscription(listID string, email string, mergeFields map[string]interface{}) (*MemberResponse, error) {
// Hash email
emailMD5 := fmt.Sprintf("%x", md5.Sum([]byte(email)))
// Make request
params := map[string]interface{}{
"email_address": email,
"status": status.Subscribed,
"merge_fields": mergeFields,
}
resp, err := c.do(
"PUT",
fmt.Sprintf("/lists/%s/members/%s", listID, emailMD5),
¶ms,
)
if err != nil {
return nil, err
}
defer resp.Body.Close()
// Read the response body
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
// Allow any success status (2xx)
if resp.StatusCode/100 == 2 {
// Unmarshal response into MemberResponse struct
memberResponse := new(MemberResponse)
if err := json.Unmarshal(data, memberResponse); err != nil {
return nil, err
}
return memberResponse, nil
}
// Request failed
errorResponse, err := extractError(data)
if err != nil {
return nil, err
}
return nil, errorResponse
}