-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
63 lines (51 loc) · 1.15 KB
/
utils.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
package openai
import (
"bytes"
"encoding/json"
"io"
"net/http"
"time"
"github.com/askasoft/pango/iox"
"github.com/askasoft/pango/str"
)
const (
contentTypeJSON = `application/json; charset="utf-8"`
)
func toJSONIndent(o any) string {
if o == nil {
return ""
}
bs, err := json.MarshalIndent(o, "", " ")
if err != nil {
return err.Error()
}
return str.UnsafeString(bs)
}
func buildJsonRequest(a any) (io.Reader, string, error) {
body, err := json.Marshal(a)
if err != nil {
return nil, "", err
}
buf := bytes.NewReader(body)
return buf, contentTypeJSON, nil
}
func decodeResponse(res *http.Response, obj any, retryAfter time.Duration) error {
defer iox.DrainAndClose(res.Body)
decoder := json.NewDecoder(res.Body)
if res.StatusCode == http.StatusOK {
if obj != nil {
return decoder.Decode(obj)
}
return nil
}
er := &ErrorResult{
Status: res.Status,
StatusCode: res.StatusCode,
}
_ = decoder.Decode(er)
switch er.StatusCode {
case http.StatusTooManyRequests, http.StatusInternalServerError, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:
er.RetryAfter = retryAfter
}
return er
}