-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreate.go
61 lines (54 loc) · 1.72 KB
/
create.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
package main
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
)
func (a *accountClient) Create(ctx context.Context, account *Account) (Account, error) {
accountPath := a.baseUrl.String() + endpointAccounts
requestMethod := http.MethodPost
acc, err := json.Marshal(&AccountWrapper{
Data: *account,
})
if err != nil {
return Account{}, &ErrInvalidRequest{requestMethod, endpointAccounts, err.Error()}
}
resp, err := a.httpClient.Post(accountPath, "application/json", bytes.NewBuffer(acc))
if err != nil {
return Account{}, newGenericAccountError(requestMethod, accountPath, err.Error(), 0)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusConflict {
return Account{}, &ErrDuplicateAccount{account}
}
if resp.StatusCode == http.StatusBadRequest {
all, err := ioutil.ReadAll(resp.Body)
if err != nil {
return Account{}, newGenericAccountError(requestMethod, accountPath, err.Error(), resp.StatusCode)
}
var respErr map[string]string
err = json.Unmarshal(all, &respErr)
if err != nil {
return Account{}, newGenericAccountError(requestMethod, accountPath, err.Error(), resp.StatusCode)
}
errStr, ok := respErr["error_message"]
if !ok {
return Account{}, newGenericAccountError(requestMethod, accountPath, err.Error(), resp.StatusCode)
}
return Account{}, &ErrInvalidRequest{
Method: requestMethod,
BaseUri: accountPath,
ErrMsg: errStr,
}
}
if resp.StatusCode != http.StatusCreated {
return Account{}, newGenericAccountError(requestMethod, accountPath, "invalid response code from api", resp.StatusCode)
}
accountResponse, err := parseAccountResponse(requestMethod, accountPath, resp)
if err != nil {
return Account{}, err
}
return accountResponse, nil
}