-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
100 lines (78 loc) · 2.08 KB
/
http.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
package openai
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"github.com/KirillMironov/openai/internal/formdata"
)
func makeJSONRequest[T any](ctx context.Context, client *Client, method, path string, payload any) (T, error) {
var (
target T
body io.Reader
)
if payload != nil {
buf := new(bytes.Buffer)
if err := json.NewEncoder(buf).Encode(payload); err != nil {
return target, err
}
body = buf
}
req, err := http.NewRequestWithContext(ctx, method, client.baseURL+path, body)
if err != nil {
return target, err
}
req.Header.Set("Content-Type", "application/json")
return makeRequest[T](client, req)
}
func makeFormDataRequest[T any](ctx context.Context, client *Client, path string, payload any) (T, error) {
var target T
data, contentType, err := formdata.Marshal(payload)
if err != nil {
return target, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, client.baseURL+path, bytes.NewReader(data))
if err != nil {
return target, err
}
req.Header.Set("Content-Type", contentType)
return makeRequest[T](client, req)
}
func makeRequest[T any](client *Client, req *http.Request) (T, error) {
var target T
req.Header.Set("Authorization", "Bearer "+client.apiKey)
if client.organization != "" {
req.Header.Set("OpenAI-Organization", client.organization)
}
resp, err := client.httpClient.Do(req)
if err != nil {
return target, err
}
defer resp.Body.Close()
respData, err := io.ReadAll(resp.Body)
if err != nil {
return target, err
}
if resp.StatusCode != http.StatusOK {
var openaiApiResponse struct {
Error struct {
Message string `json:"message"`
Type string `json:"type"`
} `json:"error"`
}
if err = json.Unmarshal(respData, &openaiApiResponse); err != nil {
return target, Error{
StatusCode: resp.StatusCode,
Message: string(respData),
Type: "unknown",
}
}
return target, Error{
StatusCode: resp.StatusCode,
Message: openaiApiResponse.Error.Message,
Type: openaiApiResponse.Error.Type,
}
}
return target, json.Unmarshal(respData, &target)
}