-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathapi.go
96 lines (78 loc) · 2.13 KB
/
api.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
package openairt
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
)
type CreateSessionRequest struct {
ClientSession
// The Realtime model used for this session.
Model string `json:"model"`
}
type ClientSecret struct {
// Ephemeral key usable in client environments to authenticate connections to the Realtime API. Use this in client-side environments rather than a standard API token, which should only be used server-side.
Value string `json:"value"`
// Timestamp for when the token expires. Currently, all tokens expire after one minute.
ExpiresAt int64 `json:"expires_at"`
}
type CreateSessionResponse struct {
ServerSession
// Ephemeral key returned by the API.
ClientSecret ClientSecret `json:"client_secret"`
}
type httpOption struct {
client *http.Client
headers http.Header
method string
}
type HTTPOption func(*httpOption)
func WithHeaders(headers http.Header) HTTPOption {
return func(o *httpOption) {
o.headers = headers
}
}
func WithClient(client *http.Client) HTTPOption {
return func(o *httpOption) {
o.client = client
}
}
func WithMethod(method string) HTTPOption {
return func(o *httpOption) {
o.method = method
}
}
func HTTPDo[Q any, R any](ctx context.Context, url string, req *Q, opts ...HTTPOption) (*R, error) {
opt := httpOption{
client: http.DefaultClient,
headers: http.Header{},
method: http.MethodPost,
}
for _, o := range opts {
o(&opt)
}
data, err := json.Marshal(req)
if err != nil {
return nil, fmt.Errorf("failed to marshal request: %w", err)
}
request, err := http.NewRequestWithContext(ctx, opt.method, url, bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
request.Header = opt.headers
response, err := opt.client.Do(request)
if err != nil {
return nil, fmt.Errorf("http failed: %w", err)
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("http status code: %d", response.StatusCode)
}
var resp R
err = json.NewDecoder(response.Body).Decode(&resp)
if err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}
return &resp, nil
}