-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_options.go
More file actions
102 lines (87 loc) · 2.34 KB
/
client_options.go
File metadata and controls
102 lines (87 loc) · 2.34 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
package flashduty
import (
"fmt"
"net/http"
"net/url"
"time"
)
// Option configures the Client
type Option func(*Client)
// WithBaseURL sets the base URL for the API client.
// Invalid URLs are validated eagerly; NewClient returns an error if parsing fails.
func WithBaseURL(baseURL string) Option {
parsedURL, err := url.Parse(baseURL)
return func(c *Client) {
if err == nil && parsedURL != nil {
c.baseURL = parsedURL
} else {
c.optionErr = fmt.Errorf("invalid base URL %q: %w", baseURL, err)
}
}
}
// WithTimeout sets the HTTP client timeout
func WithTimeout(d time.Duration) Option {
return func(c *Client) {
c.httpClient.Timeout = d
}
}
// WithUserAgent sets the User-Agent header
func WithUserAgent(ua string) Option {
return func(c *Client) {
c.userAgent = ua
}
}
// WithHTTPClient sets a custom HTTP client. Nil values are ignored.
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) {
if hc != nil {
c.httpClient = hc
}
}
}
// WithLogger sets a custom logger for the SDK client. Nil values are ignored.
func WithLogger(l Logger) Option {
return func(c *Client) {
if l != nil {
c.logger = l
}
}
}
// WithRequestHeaders sets static headers that will be included in every API request.
// These are applied after the SDK's own headers (Content-Type, Accept, User-Agent).
func WithRequestHeaders(headers http.Header) Option {
return func(c *Client) {
c.requestHeaders = headers
}
}
// WithRequestHook sets a callback invoked on every outgoing HTTP request before it is sent.
// Use this to inject per-request headers such as W3C Trace Context (traceparent/tracestate).
// The hook receives the fully constructed *http.Request and may modify headers or other fields.
func WithRequestHook(hook func(*http.Request)) Option {
return func(c *Client) {
c.requestHook = hook
}
}
// NewClient creates a new Flashduty API client
func NewClient(appKey string, opts ...Option) (*Client, error) {
if appKey == "" {
return nil, fmt.Errorf("APP key is required")
}
baseURL, _ := url.Parse("https://api.flashcat.cloud")
c := &Client{
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
baseURL: baseURL,
appKey: appKey,
userAgent: "flashduty-go-sdk",
logger: defaultLogger,
}
for _, opt := range opts {
opt(c)
}
if c.optionErr != nil {
return nil, c.optionErr
}
return c, nil
}