-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
111 lines (91 loc) · 2.15 KB
/
client.go
File metadata and controls
111 lines (91 loc) · 2.15 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
109
110
111
package mefrpApi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
const (
BaseURL = "https://api.mefrp.com/api"
)
type Client struct {
httpClient *http.Client
token string
baseURL string
userAgent string
}
type Option func(*Client)
func WithTimeout(timeout time.Duration) Option {
return func(c *Client) {
c.httpClient.Timeout = timeout
}
}
func WithBaseURL(url string) Option {
return func(c *Client) {
c.baseURL = url
}
}
func WithUserAgent(userAgent string) Option {
return func(c *Client) {
c.userAgent = userAgent
}
}
func NewClient(token string, opts ...Option) *Client {
c := &Client{
httpClient: &http.Client{
Timeout: 10 * time.Second,
},
token: token,
baseURL: BaseURL,
userAgent: "MEFrp-Golang-SDK/" + Version,
}
for _, opt := range opts {
opt(c)
}
return c
}
// SetBaseURL updates the base URL for the client
func (c *Client) SetBaseURL(url string) {
c.baseURL = url
}
// SetToken updates the authentication token for the client
func (c *Client) SetToken(token string) {
c.token = token
}
// SetUserAgent updates the user agent for the client
func (c *Client) SetUserAgent(userAgent string) {
c.userAgent = userAgent
}
func (c *Client) request(method, path string, body interface{}, v interface{}) error {
var reqBody io.Reader
if body != nil {
jsonBytes, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("failed to marshal request body: %w", err)
}
reqBody = bytes.NewBuffer(jsonBytes)
}
req, err := http.NewRequest(method, c.baseURL+path, reqBody)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", c.userAgent)
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized {
return fmt.Errorf("unauthorized: invalid token")
}
if v != nil {
if err := json.NewDecoder(resp.Body).Decode(v); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
}
return nil
}