/
client.go
56 lines (45 loc) · 1.27 KB
/
client.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
package luadns
import (
"context"
"encoding/json"
"fmt"
)
// OptFunc represents a configuration function which are used to configure the REST API client.
type OptFunc func(*Client)
// SetBaseURL sets a custom baseURL for API requests (used in unit tests).
func SetBaseURL(url string) OptFunc {
return func(c *Client) {
c.baseURL = url
}
}
// RestCallFunc represents a call to REST API.
type RestCallFunc func() ([]byte, error)
// Client represents a REST API client for LuaDNS API.
type Client struct {
baseURL string
client *JSONClient
}
// NewClient initializes the REST API client with supplied context and configures authentication.
func NewClient(ctx context.Context, email, apiKey string, opts ...OptFunc) *Client {
c := &Client{
baseURL: baseURL,
client: NewAuthJSONClient(ctx, email, apiKey),
}
// Apply custom options.
for _, opt := range opts {
opt(c)
}
return c
}
// endpoint is a helper which builds the endpoint URL.
func (c *Client) endpoint(format string, args ...any) string {
return c.baseURL + fmt.Sprintf(format, args...)
}
// do executes REST call and serializes the response into `dest` target.
func (c *Client) do(fn RestCallFunc, dest any) error {
data, err := fn()
if err != nil {
return err
}
return json.Unmarshal(data, &dest)
}