Files
coder/aibridge/utils/http.go
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

34 lines
957 B
Go
Raw Normal View History

package utils
import (
"bytes"
"fmt"
"io"
"math"
"net/http"
"strconv"
"time"
)
// NewJSONErrorResponse builds an *http.Response with a JSON body
// and optional Retry-After header. Used to synthesize bridge-side
// error responses (e.g. key-pool exhaustion, marshaling
// fallbacks). Retry-After is set to whole seconds (rounded up)
// when retryAfter is positive, and omitted otherwise.
func NewJSONErrorResponse(status int, retryAfter time.Duration, body []byte) *http.Response {
h := http.Header{}
h.Set("Content-Type", "application/json")
if retryAfter > 0 {
h.Set("Retry-After", strconv.Itoa(int(math.Ceil(retryAfter.Seconds()))))
}
return &http.Response{
Status: fmt.Sprintf("%d %s", status, http.StatusText(status)),
StatusCode: status,
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
Header: h,
Body: io.NopCloser(bytes.NewReader(body)),
ContentLength: int64(len(body)),
}
}