-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
109 lines (97 loc) · 2.36 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
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
package coze
import (
"net/http"
)
type CozeAPI struct {
Audio *audio
Bots *bots
Chat *chat
Conversations *conversations
Workflows *workflows
Workspaces *workspace
Datasets *datasets
Files *files
Templates *templates
baseURL string
}
type newCozeAPIOpt struct {
baseURL string
client *http.Client
logLevel LogLevel
}
type CozeAPIOption func(*newCozeAPIOpt)
// WithBaseURL adds the base URL for the API
func WithBaseURL(baseURL string) CozeAPIOption {
return func(opt *newCozeAPIOpt) {
opt.baseURL = baseURL
}
}
// WithHttpClient sets a custom HTTP core
func WithHttpClient(client *http.Client) CozeAPIOption {
return func(opt *newCozeAPIOpt) {
opt.client = client
}
}
// WithLogLevel sets the logging level
func WithLogLevel(level LogLevel) CozeAPIOption {
return func(opt *newCozeAPIOpt) {
opt.logLevel = level
}
}
func WithLogger(logger Logger) CozeAPIOption {
return func(opt *newCozeAPIOpt) {
setLogger(logger)
}
}
func NewCozeAPI(auth Auth, opts ...CozeAPIOption) CozeAPI {
opt := &newCozeAPIOpt{
baseURL: ComBaseURL,
logLevel: LogLevelInfo, // Default log level is Info
}
for _, option := range opts {
option(opt)
}
if opt.client == nil {
opt.client = &http.Client{}
}
saveTransport := opt.client.Transport
if saveTransport == nil {
saveTransport = http.DefaultTransport
}
opt.client.Transport = &authTransport{
auth: auth,
next: saveTransport,
}
core := newCore(opt.client, opt.baseURL)
setLevel(opt.logLevel)
// Set log level
cozeClient := CozeAPI{
Audio: newAudio(core),
Bots: newBots(core),
Chat: newChats(core),
Conversations: newConversations(core),
Workflows: newWorkflows(core),
Workspaces: newWorkspace(core),
Datasets: newDatasets(core),
Files: newFiles(core),
Templates: newTemplates(core),
baseURL: opt.baseURL,
}
return cozeClient
}
type authTransport struct {
auth Auth
next http.RoundTripper
}
func (h *authTransport) RoundTrip(req *http.Request) (*http.Response, error) {
if isAuthContext(req.Context()) {
return h.next.RoundTrip(req)
}
accessToken, err := h.auth.Token(req.Context())
if err != nil {
logger.Errorf(req.Context(), "Failed to get access token: %v", err)
return nil, err
}
req.Header.Set("Authorization", "Bearer "+accessToken)
return h.next.RoundTrip(req)
}