87 lines
2.6 KiB
Go
87 lines
2.6 KiB
Go
package orbit
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// Options 配置传输与命名空间凭据;健康查询不使用凭据。
|
|
type Options struct {
|
|
HTTPClient *http.Client
|
|
Token string
|
|
}
|
|
type Client struct {
|
|
baseURL string
|
|
http *http.Client
|
|
token string
|
|
}
|
|
type Health struct {
|
|
Status string `json:"status"`
|
|
Scope string `json:"scope,omitempty"`
|
|
}
|
|
|
|
// HTTPError exposes the status code without including sensitive response bodies.
|
|
type HTTPError struct{ StatusCode int }
|
|
|
|
func (e *HTTPError) Error() string { return fmt.Sprintf("orbit returned HTTP %d", e.StatusCode) }
|
|
|
|
func NewClient(baseURL string, opts Options) (*Client, error) {
|
|
u, err := url.Parse(baseURL)
|
|
if err != nil || u == nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") || u.User != nil || u.RawQuery != "" || u.Fragment != "" {
|
|
return nil, errors.New("Orbit base URL must be absolute HTTP(S), without credentials, query or fragment")
|
|
}
|
|
if len(opts.Token) > 1024 || strings.ContainsAny(opts.Token, " \t\r\n") {
|
|
return nil, errors.New("invalid Orbit token")
|
|
}
|
|
client := opts.HTTPClient
|
|
if client == nil {
|
|
client = &http.Client{Timeout: 10 * time.Second}
|
|
}
|
|
clone := *client
|
|
// Do not silently forward requests to another origin through redirects.
|
|
clone.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
|
return &Client{baseURL: strings.TrimRight(u.String(), "/"), http: &clone, token: opts.Token}, nil
|
|
}
|
|
func (c *Client) Liveness(ctx context.Context) (Health, error) { return c.health(ctx, "/health/live") }
|
|
func (c *Client) Readiness(ctx context.Context) (Health, error) {
|
|
return c.health(ctx, "/health/ready")
|
|
}
|
|
func (c *Client) health(ctx context.Context, path string) (Health, error) {
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
|
|
if err != nil {
|
|
return Health{}, err
|
|
}
|
|
req.Header.Set("Accept", "application/json")
|
|
response, err := c.http.Do(req)
|
|
if err != nil {
|
|
return Health{}, err
|
|
}
|
|
defer response.Body.Close()
|
|
if response.StatusCode != http.StatusOK {
|
|
return Health{}, &HTTPError{StatusCode: response.StatusCode}
|
|
}
|
|
const maxBody = 16 << 10
|
|
body, err := io.ReadAll(io.LimitReader(response.Body, maxBody+1))
|
|
if err != nil {
|
|
return Health{}, err
|
|
}
|
|
if len(body) > maxBody {
|
|
return Health{}, errors.New("Orbit health response exceeds limit")
|
|
}
|
|
var health Health
|
|
if err := json.Unmarshal(body, &health); err != nil {
|
|
return Health{}, fmt.Errorf("decode Orbit health response: %w", err)
|
|
}
|
|
if health.Status == "" {
|
|
return Health{}, errors.New("Orbit health response is missing status")
|
|
}
|
|
return health, nil
|
|
}
|