-
Notifications
You must be signed in to change notification settings - Fork 1
/
rest.go
73 lines (62 loc) · 1.33 KB
/
rest.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
package banana
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type errJSON struct {
Message string
}
func post(ctx context.Context, url string, p interface{}, re interface{}) error {
// Marshal the payload
jsonBytes, err := json.Marshal(p)
if err != nil {
return err
}
req, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(jsonBytes))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// Post it
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
// Catch non-200 status codes
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == 500 {
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
errStruct := errJSON{}
err = json.Unmarshal(bodyBytes, &errStruct)
if err != nil {
return err
}
return fmt.Errorf(
"banana returned status code %v with message:%s",
resp.StatusCode,
errStruct.Message,
)
}
return fmt.Errorf("banana returned status code %v", resp.StatusCode)
}
// Read body into bytes
defer resp.Body.Close()
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
// Parse returned bytes into the struct
err = json.Unmarshal(bodyBytes, re)
if err != nil {
return err
}
return nil
}