FloorVisualizer/internal/openrouter/client.go
dindang 94895cbc22 Initial commit: FloorVisualizer backend
- Go API server with PostgreSQL + Redis
- AI floor replacement (OpenRouter Gemini)
- Product database (10 brands, 3539 products)
- Recommendation engine, calculator, articles
- Redis async queue + worker pool
- Hot product caching, brand view tracking
- JWT auth, favorites, projects
- Docker deployment ready

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-16 09:47:11 +08:00

75 lines
1.6 KiB
Go

package openrouter
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)
const defaultBaseURL = "https://openrouter.ai/api/v1"
type Client struct {
apiKey string
baseURL string
httpClient *http.Client
}
type Option func(*Client)
func WithBaseURL(u string) Option {
return func(c *Client) { c.baseURL = u }
}
func WithHTTPClient(hc *http.Client) Option {
return func(c *Client) { c.httpClient = hc }
}
func NewClient(apiKey string, opts ...Option) *Client {
c := &Client{
apiKey: apiKey,
baseURL: defaultBaseURL,
httpClient: http.DefaultClient,
}
for _, o := range opts {
o(c)
}
return c
}
func (c *Client) do(ctx context.Context, path string, reqBody, respBody any) error {
data, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("openrouter: marshal request: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL+path, bytes.NewReader(data))
if err != nil {
return fmt.Errorf("openrouter: build request: %w", err)
}
req.Header.Set("Authorization", "Bearer "+c.apiKey)
req.Header.Set("Content-Type", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return fmt.Errorf("openrouter: send request: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("openrouter: read response: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return fmt.Errorf("openrouter: HTTP %d: %s", resp.StatusCode, body)
}
if err := json.Unmarshal(body, respBody); err != nil {
return fmt.Errorf("openrouter: unmarshal response: %w\nbody: %s", err, body)
}
return nil
}