-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
49 lines (39 loc) · 1000 Bytes
/
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
package openai
import (
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
)
func httpRequest(method, url, apiKey string) (*http.Request, error) {
req, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", apiKey))
return req, nil
}
type httpErrorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
Param any `json:"param"`
Type string `json:"type"`
}
type httpErrorResponse struct {
Error httpErrorDetail `json:"error"`
}
func handleHTTPResponse(response *http.Response) error {
if response.StatusCode < 400 {
return nil
}
body, err := io.ReadAll(response.Body)
if err != nil {
return fmt.Errorf("failed to read response body: %w", err)
}
var parsedResponse httpErrorResponse
if err := json.Unmarshal(body, &parsedResponse); err != nil {
return fmt.Errorf("failed to parse response body: %w", err)
}
return errors.New(parsedResponse.Error.Message)
}