-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
97 lines (81 loc) · 2.11 KB
/
Copy pathapi.go
File metadata and controls
97 lines (81 loc) · 2.11 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package apimate
import (
"fmt"
"github.com/rollicks-c/apimate/internal/client"
"net/http"
"strings"
)
type Option = client.RequestOption
type JsonBool = client.JsonBool
type JsonInt64 = client.JsonInt64
func WithAllPages(pageParam, pagesHeader string) client.RequestOption {
return func(ctx *client.RequestContext) error {
ctx.Paging.ConsumeAll = true
ctx.Paging.PageParam = pageParam
ctx.Paging.PageCountHeader = pagesHeader
return nil
}
}
func WithAcceptedErrors(codes ...int) client.RequestOption {
checker := func(resp *http.Response) bool {
for _, c := range codes {
if c == resp.StatusCode {
return true
}
}
return false
}
return func(ctx *client.RequestContext) error {
ctx.StatusChecker = checker
return nil
}
}
func WithStatusChecker(checker client.StatusChecker) client.RequestOption {
return func(ctx *client.RequestContext) error {
ctx.StatusChecker = checker
return nil
}
}
type Client struct {
apiUrl string
defaultOptions []client.RequestOption
}
func New(apiUrl string, defaults ...client.RequestOption) *Client {
return &Client{
apiUrl: apiUrl,
defaultOptions: defaults,
}
}
func (c Client) Request(method, ep string, options ...client.RequestOption) error {
// create context with default options
ctx := &client.RequestContext{
ApiUrl: c.apiUrl,
Method: method,
Endpoint: fmt.Sprintf("%s/%s", strings.TrimSuffix(c.apiUrl, "/"), strings.TrimPrefix(ep, "/")),
AutoThrottle: true,
AutoRetries: 3,
Paging: client.PagingConfig{ConsumeAll: false},
DefaultOptions: c.defaultOptions,
ResponseProcessors: []client.ResponseProcessor{},
SkipTLSVerify: false,
}
// apply defaults options
defaults := []client.RequestOption{
WithDefaultRequest(),
WithNullReceiver(),
WithAcceptedErrors(),
}
// apply custom options
options = append(defaults, options...)
for _, option := range options {
if err := option(ctx); err != nil {
return err
}
}
// execute
runner := client.NewRunner(*ctx)
if err := runner.DoRequest(); err != nil {
return err
}
return nil
}