package ai import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "time" ) // client is a small LLM HTTP client with a bounded response size and a // timeout so a slow or chatty upstream cannot hang a scan. type client struct { httpc *http.Client } func newClient() *client { return &client{httpc: &http.Client{Timeout: 60 * time.Second}} } // postJSON sends payload as JSON and decodes the response body into out. func (c *client) postJSON(ctx context.Context, url string, headers map[string]string, payload, out any) error { body, err := json.Marshal(payload) if err != nil { return fmt.Errorf("ai: encode request: %w", err) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) if err != nil { return fmt.Errorf("ai: %w", err) } req.Header.Set("Content-Type", "application/json") for k, v := range headers { req.Header.Set(k, v) } resp, err := c.httpc.Do(req) if err != nil { return fmt.Errorf("ai: %w", err) } defer resp.Body.Close() data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) // 4 MiB cap if err != nil { return fmt.Errorf("ai: read response: %w", err) } if resp.StatusCode < 200 || resp.StatusCode >= 300 { return fmt.Errorf("ai: %s: %s", resp.Status, strings.TrimSpace(string(data))) } if err := json.Unmarshal(data, out); err != nil { return fmt.Errorf("ai: decode response: %w", err) } return nil }