-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple_api.go
More file actions
40 lines (33 loc) · 813 Bytes
/
simple_api.go
File metadata and controls
40 lines (33 loc) · 813 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
package example
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
)
func CallAPI(ctx context.Context, rootURL string, input map[string]interface{}) (map[string]interface{}, error) {
bodyBytes, err := json.Marshal(input)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, rootURL+"/animal", bytes.NewReader(bodyBytes))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
if res.StatusCode != http.StatusOK {
err := errors.New("not found")
return nil, err
}
data := map[string]interface{}{}
decoder := json.NewDecoder(res.Body)
if err := decoder.Decode(&data); err != nil {
return nil, err
}
return data, nil
}