forked from reVrost/go-openrouter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
191 lines (157 loc) · 4.12 KB
/
client.go
File metadata and controls
191 lines (157 loc) · 4.12 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
package openrouter
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
)
type Client[Schema any] struct {
config ClientConfig
requestBuilder RequestBuilder
}
func NewClient[Schema any](auth string, opts ...Option) *Client[Schema] {
config := DefaultConfig(auth)
for _, opt := range opts {
opt(config)
}
return NewClientWithConfig[Schema](*config)
}
func NewClientWithConfig[Schema any](config ClientConfig) *Client[Schema] {
return &Client[Schema]{
config: config,
requestBuilder: NewRequestBuilder(),
}
}
func (c *Client[Schema]) sendRequest(req *http.Request, v any) error {
req.Header.Set("Accept", "application/json; charset=utf-8")
// Check whether Content-Type is already set, Upload Files API requires
// Content-Type == multipart/form-data
contentType := req.Header.Get("Content-Type")
if contentType == "" {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
c.setCommonHeaders(req)
res, err := c.config.HTTPClient.Do(req)
if err != nil {
return err
}
defer res.Body.Close()
if isFailureStatusCode(res) {
return c.handleErrorResp(res)
}
return decodeResponse(res.Body, v)
}
func (c *Client[Schema]) setCommonHeaders(req *http.Request) {
req.Header.Set("HTTP-Referer", c.config.HttpReferer)
req.Header.Set("X-Title", c.config.XTitle)
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.config.authToken))
}
func isFailureStatusCode(resp *http.Response) bool {
return resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest
}
func decodeResponse(body io.Reader, v any) error {
if v == nil {
return nil
}
if result, ok := v.(*string); ok {
return decodeString(body, result)
}
return json.NewDecoder(body).Decode(v)
}
func decodeString(body io.Reader, output *string) error {
b, err := io.ReadAll(body)
if err != nil {
return err
}
*output = string(b)
return nil
}
type fullUrlOptions struct {
query url.Values
}
type fullUrlOption func(*fullUrlOptions)
func withQuery(query url.Values) fullUrlOption {
return func(args *fullUrlOptions) {
args.query = query
}
}
// fullURL returns full URL for request.
func (c *Client[Schema]) fullURL(suffix string, setters ...fullUrlOption) string {
// Default Options
args := &fullUrlOptions{
query: nil,
}
for _, setter := range setters {
setter(args)
}
if args.query != nil {
suffix = fmt.Sprintf("%s?%s", suffix, args.query.Encode())
}
return fmt.Sprintf("%s%s", c.config.BaseURL, suffix)
}
type requestOptions struct {
body any
header http.Header
}
type requestOption func(*requestOptions)
func withBody(body any) requestOption {
return func(args *requestOptions) {
args.body = body
}
}
func withContentType(contentType string) requestOption {
return func(args *requestOptions) {
args.header.Set("Content-Type", contentType)
}
}
func (c *Client[Schema]) newRequest(ctx context.Context, method, url string, setters ...requestOption) (*http.Request, error) {
// Default Options
args := &requestOptions{
body: nil,
header: make(http.Header),
}
for _, setter := range setters {
setter(args)
}
req, err := c.requestBuilder.Build(ctx, method, url, args.body, args.header)
if err != nil {
return nil, err
}
c.setCommonHeaders(req)
return req, nil
}
func (c *Client[Schema]) newStreamRequest(
ctx context.Context,
method string,
urlSuffix string,
body any) (*http.Request, error) {
req, err := c.requestBuilder.Build(ctx, method, c.fullURL(urlSuffix), body, http.Header{
"Content-Type": []string{"application/json"},
"Accept": []string{"text/event-stream"},
"Cache-Control": []string{"no-cache"},
"Connection": []string{"keep-alive"},
})
if err != nil {
return nil, err
}
c.setCommonHeaders(req)
return req, nil
}
func (c *Client[Schema]) handleErrorResp(resp *http.Response) error {
var errRes ErrorResponse
err := json.NewDecoder(resp.Body).Decode(&errRes)
if err != nil || errRes.Error == nil {
reqErr := &RequestError{
HTTPStatusCode: resp.StatusCode,
Err: err,
}
if errRes.Error != nil {
reqErr.Err = errRes.Error
}
return reqErr
}
errRes.Error.HTTPStatusCode = resp.StatusCode
return errRes.Error
}