package semble import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" ) const DefaultBaseURL = "https://api.semble.so/xrpc" type AuthProvider interface { Apply(*http.Request) error } type APIKeyAuth string func (a APIKeyAuth) Apply(r *http.Request) error { if a != "" { r.Header.Set("x-api-key", string(a)) } return nil } type BearerAuth string func (b BearerAuth) Apply(r *http.Request) error { if b != "" { r.Header.Set("Authorization", "Bearer "+string(b)) } return nil } type NoAuth struct{} func (NoAuth) Apply(*http.Request) error { return nil } type Client struct { BaseURL *url.URL HTTPClient *http.Client Auth AuthProvider } type Option func(*Client) error func WithBaseURL(raw string) Option { return func(c *Client) error { u, err := url.Parse(raw) if err != nil { return err } c.BaseURL = u return nil } } func WithHTTPClient(h *http.Client) Option { return func(c *Client) error { if h != nil { c.HTTPClient = h } return nil } } func WithAuth(a AuthProvider) Option { return func(c *Client) error { c.Auth = a return nil } } func WithAPIKey(k string) Option { return WithAuth(APIKeyAuth(k)) } func New(opts ...Option) (*Client, error) { u, _ := url.Parse(DefaultBaseURL) c := &Client{ BaseURL: u, HTTPClient: http.DefaultClient, Auth: NoAuth{}, } for _, opt := range opts { if err := opt(c); err != nil { return nil, err } } return c, nil } // APIError describes a non-2xx Semble API response. type APIError struct { StatusCode int Status string Body []byte Message string `json:"message,omitempty"` ErrorMessage string `json:"error,omitempty"` } func (e *APIError) Error() string { msg := e.Message if msg == "" { msg = e.ErrorMessage } if msg == "" { msg = strings.TrimSpace(string(e.Body)) } if msg == "" { msg = e.Status } return fmt.Sprintf("semble: %s", msg) } func (c *Client) get(ctx context.Context, nsid string, q url.Values, out any) error { return c.do(ctx, http.MethodGet, nsid, q, nil, out) } func (c *Client) post(ctx context.Context, nsid string, body any, out any) error { return c.do(ctx, http.MethodPost, nsid, nil, body, out) } func (c *Client) do( ctx context.Context, method string, nsid string, q url.Values, body any, out any, ) error { u := *c.BaseURL u.Path = strings.TrimRight(c.BaseURL.Path, "/") + "/" + nsid if q != nil { u.RawQuery = q.Encode() } var r io.Reader if body != nil { b, err := json.Marshal(body) if err != nil { return err } r = bytes.NewReader(b) } req, err := http.NewRequestWithContext(ctx, method, u.String(), r) if err != nil { return err } req.Header.Set("Accept", "application/json") if body != nil { req.Header.Set("Content-Type", "application/json") } if c.Auth != nil { if err := c.Auth.Apply(req); err != nil { return err } } resp, err := c.HTTPClient.Do(req) if err != nil { return err } defer func() { _ = resp.Body.Close() }() data, err := io.ReadAll(resp.Body) if err != nil { return err } if resp.StatusCode < 200 || resp.StatusCode > 299 { ae := &APIError{ StatusCode: resp.StatusCode, Status: resp.Status, Body: data, } _ = json.Unmarshal(data, ae) return ae } if out == nil || len(data) == 0 { return nil } return json.Unmarshal(data, out) } func values(opts ...Query) url.Values { v := url.Values{} for _, opt := range opts { opt(v) } return v } type Query func(url.Values) func qp(k string, val any) Query { return func(v url.Values) { switch x := val.(type) { case string: if x != "" { v.Set(k, x) } case int: if x != 0 { v.Set(k, fmt.Sprint(x)) } case bool: v.Set(k, fmt.Sprint(x)) case float64: if x != 0 { v.Set(k, fmt.Sprint(x)) } } } } func qps(k string, vals []string) Query { return func(v url.Values) { for _, s := range vals { if s != "" { v.Add(k, s) } } } } func pagination(p PageQuery) []Query { return []Query{ qp("page", p.Page), qp("limit", p.Limit), qp("sortBy", p.SortBy), qp("sortOrder", p.SortOrder), } }