-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.go
More file actions
52 lines (42 loc) · 905 Bytes
/
struct.go
File metadata and controls
52 lines (42 loc) · 905 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
47
48
49
50
51
52
package example
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
)
type API struct {
RootURL string
}
type Request struct {
Name string `json:"name"`
}
type Response struct {
ID string `json:"id"`
}
func (api *API) Call(ctx context.Context, input Request) (*Response, error) {
bodyBytes, err := json.Marshal(input)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, api.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
}
var data Response
decoder := json.NewDecoder(res.Body)
if err := decoder.Decode(&data); err != nil {
return nil, err
}
return &data, nil
}