-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
90 lines (68 loc) · 1.83 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
package openai
import (
"encoding/json"
"fmt"
"net/http"
)
type Client struct {
config ClientConfig
}
func NewClient(apiAuthToken string) *Client {
config := DefaultConfig(apiAuthToken)
return NewClientWithConfig(config)
}
func NewClientWithConfig(config ClientConfig) *Client {
return &Client{
config: config,
}
}
func (c *Client) sendRequest(req *http.Request, v any) error {
c.setDefaultHeader(req)
res, err := c.config.HTTPClient.Do(req)
if err != nil {
return fmt.Errorf("sending request: %w", err)
}
defer res.Body.Close()
if isFailureStatusCode(res) {
return c.handleErrorResp(res)
}
if v != nil {
if err = json.NewDecoder(res.Body).Decode(v); err != nil {
return fmt.Errorf("decoding response: %w", err)
}
}
return nil
}
func (c *Client) getFullURL(suffix string) string {
return fmt.Sprintf("%s%s", c.config.BaseURL, suffix)
}
func (c *Client) setDefaultHeader(req *http.Request) {
req.Header.Set("Accept", "application/json; charset=utf-8")
req.Header.Set("Authorization", "Bearer "+c.config.apiAuthToken)
contentType := req.Header.Get("Content-Type")
if contentType == "" {
req.Header.Set("Content-Type", "application/json; charset=utf-8")
}
if c.config.Organization != "" {
req.Header.Set("OpenAI-Organization", c.config.Organization)
}
}
func (c *Client) 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
}
func isFailureStatusCode(resp *http.Response) bool {
return resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusBadRequest
}