xonecas.io
6312
Ga

go-opencode-ai-zen-sdk / files

go-opencode-ai-zen-sdk / http.go

2.1 KB
1package zen
2
3import (
4	"bytes"
5	"context"
6	"encoding/json"
7	"io"
8	"net/http"
9	"strings"
10	"time"
11)
12
13var retryableStatus = map[int]bool{
14	http.StatusTooManyRequests:     true,
15	http.StatusInternalServerError: true,
16	http.StatusBadGateway:          true,
17	http.StatusServiceUnavailable:  true,
18	http.StatusGatewayTimeout:      true,
19}
20
21func (c *Client) doRequest(ctx context.Context, method, path string, body []byte, endpoint EndpointType, forceAllAuth bool) ([]byte, http.Header, error) {
22	url := joinURL(c.cfg.BaseURL, path)
23	if body == nil {
24		body = []byte{}
25	}
26
27	retries := c.cfg.Retry.MaxRetries
28	if !isIdempotent(method) && !c.cfg.Retry.RetryOnNonIdempotent {
29		retries = 0
30	}
31
32	var lastErr error
33	for attempt := 0; attempt <= retries; attempt++ {
34		req, err := http.NewRequestWithContext(ctx, method, url, bytes.NewReader(body))
35		if err != nil {
36			return nil, nil, err
37		}
38
39		c.applyRequestHeaders(req, endpoint, false, forceAllAuth)
40
41		resp, err := c.httpClient.Do(req)
42		if err != nil {
43			lastErr = err
44			if attempt < retries {
45				time.Sleep(c.cfg.Retry.Backoff(attempt))
46				continue
47			}
48			return nil, nil, err
49		}
50
51		payload, readErr := io.ReadAll(resp.Body)
52		_ = resp.Body.Close()
53		if readErr != nil {
54			return nil, resp.Header, readErr
55		}
56
57		if resp.StatusCode >= 200 && resp.StatusCode < 300 {
58			return payload, resp.Header, nil
59		}
60
61		apiErr := newAPIError(resp.StatusCode, resp.Header, payload)
62		lastErr = apiErr
63		if attempt < retries && retryableStatus[resp.StatusCode] {
64			time.Sleep(c.cfg.Retry.Backoff(attempt))
65			continue
66		}
67		return nil, resp.Header, apiErr
68	}
69
70	return nil, nil, lastErr
71}
72
73func jsonBody(v any, raw json.RawMessage) ([]byte, error) {
74	if raw != nil {
75		return raw, nil
76	}
77	if v == nil {
78		return []byte("{}"), nil
79	}
80	return json.Marshal(v)
81}
82
83func joinURL(base, path string) string {
84	if strings.HasPrefix(path, "/") {
85		return base + path
86	}
87	return base + "/" + path
88}
89
90func isIdempotent(method string) bool {
91	switch strings.ToUpper(method) {
92	case http.MethodGet, http.MethodHead, http.MethodOptions:
93		return true
94	default:
95		return false
96	}
97}