-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplunk.go
More file actions
108 lines (93 loc) · 2.32 KB
/
plunk.go
File metadata and controls
108 lines (93 loc) · 2.32 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
98
99
100
101
102
103
104
105
106
107
108
// Package plunk provides a Go client for the Plunk API.
//
// See https://docs.useplunk.com for API documentation.
package plunk
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"strings"
)
const defaultBaseURL = "https://next-api.useplunk.com"
// Option configures a [Client].
type Option interface {
apply(*Client)
}
// OptionFunc is an adapter to allow the use of ordinary functions as [Option]s.
type OptionFunc func(*Client)
func (f OptionFunc) apply(c *Client) { f(c) }
// WithBaseURL returns an [Option] that sets the base URL of the API. Trailing
// slashes are trimmed.
func WithBaseURL(url string) Option {
return OptionFunc(func(c *Client) {
c.BaseURL = strings.TrimRight(url, "/")
})
}
// WithHTTPClient returns an [Option] that sets the HTTP client used for
// requests.
func WithHTTPClient(hc *http.Client) Option {
return OptionFunc(func(c *Client) {
c.HTTPClient = hc
})
}
// Client is a Plunk API client. Use [New] to create one.
type Client struct {
APIKey string
BaseURL string
HTTPClient *http.Client
}
// New creates a new Plunk API client with the given API key and options.
func New(apiKey string, opts ...Option) *Client {
c := &Client{
APIKey: apiKey,
BaseURL: defaultBaseURL,
HTTPClient: http.DefaultClient,
}
for _, o := range opts {
o.apply(c)
}
return c
}
func (c *Client) do(ctx context.Context, method, path string, reqBody, respBody any) error {
var bodyReader io.Reader
if reqBody != nil {
body, err := json.Marshal(reqBody)
if err != nil {
return err
}
bodyReader = bytes.NewReader(body)
}
req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, bodyReader)
if err != nil {
return err
}
if reqBody != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Authorization", "Bearer "+c.APIKey)
resp, err := c.HTTPClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
data, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
apiErr := &Error{StatusCode: resp.StatusCode}
if err := json.Unmarshal(data, apiErr); err != nil {
return &Error{
StatusCode: resp.StatusCode,
Message: string(data),
}
}
return apiErr
}
if respBody != nil && len(data) > 0 {
return json.Unmarshal(data, respBody)
}
return nil
}