-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlibrary.go
74 lines (61 loc) · 1.5 KB
/
library.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
74
// Package library ...
package main // should be "package library", but gonew doesn't support it
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
)
type httpClient interface {
Do(req *http.Request) (*http.Response, error)
}
// MyStruct ...
type MyStruct struct {
userAgent string
url string
httpClient httpClient
}
// NewMyStruct creates a new MyStruct ...
func NewMyStruct(
httpClient httpClient,
userAgent string,
url string,
) (*MyStruct, error) {
return &MyStruct{
httpClient: httpClient,
userAgent: userAgent,
url: url,
}, nil
}
// MyRequest ...
type MyRequest struct {
Field string `json:"field"`
}
// MyResponse ...
type MyResponse struct {
Field string `json:"field"`
}
// DoSomething ...
func (s *MyStruct) DoSomething(r MyRequest) (*MyResponse, error) {
b, err := json.Marshal(r)
if err != nil {
return nil, fmt.Errorf("failed to encode request: %w", err)
}
req, err := http.NewRequest("POST", s.url, bytes.NewBuffer(b))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("User-Agent", s.userAgent)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := s.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
var response MyResponse
if err := json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &response, nil
}