d1abd2b15d
Co-authored-by: Cursor <cursoragent@cursor.com>
56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package remote
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type ClientConfig struct {
|
|
URL string
|
|
Token string
|
|
Timeout time.Duration
|
|
}
|
|
|
|
type Client struct {
|
|
cfg ClientConfig
|
|
}
|
|
|
|
func NewClient(cfg ClientConfig) Client {
|
|
if cfg.Timeout <= 0 {
|
|
cfg.Timeout = 5 * time.Second
|
|
}
|
|
return Client{cfg: cfg}
|
|
}
|
|
|
|
func (c Client) Report(ctx context.Context, report StatusReport) error {
|
|
body, err := json.Marshal(report)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
url := strings.TrimRight(c.cfg.URL, "/") + "/api/v1/status"
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
if c.cfg.Token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+c.cfg.Token)
|
|
}
|
|
|
|
client := &http.Client{Timeout: c.cfg.Timeout}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
if resp.StatusCode < 200 || resp.StatusCode > 299 {
|
|
return fmt.Errorf("remote report failed: %s", resp.Status)
|
|
}
|
|
return nil
|
|
}
|