-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdo_post.go
More file actions
46 lines (39 loc) · 941 Bytes
/
do_post.go
File metadata and controls
46 lines (39 loc) · 941 Bytes
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
package bulwarkadmin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
func doPost(ctx context.Context, url string, payload interface{}, model interface{}, client *http.Client) error {
jsonData, err := json.Marshal(payload)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(jsonData))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 300 {
jsonError := &JsonError{}
if err := json.NewDecoder(resp.Body).Decode(jsonError); err != nil {
return err
}
if jsonError != nil {
return fmt.Errorf("%s - %s", jsonError.Title, jsonError.Detail)
}
}
if resp.Body != http.NoBody && model != nil {
if err := json.NewDecoder(resp.Body).Decode(model); err != nil {
return err
}
}
return nil
}