sdk/client.go

62 lines
1.3 KiB
Go
Raw Normal View History

package sdk
import (
"fmt"
2026-09-13 10:53:42 +02:00
"mime"
"net/http"
"net/url"
2026-09-13 10:53:42 +02:00
"strings"
)
2026-09-13 10:53:42 +02:00
// NewClient returns an HTTP client that resolves relative request URLs against
// base and sets the Authorization header to "Bearer token" on every request.
func NewClient(base, token string) *Client {
return &Client{
Client: &http.Client{},
base: base,
token: fmt.Sprintf("Bearer %s", token),
}
}
func (a *Action) Client() *Client {
2024-11-01 23:38:54 +01:00
context := a.Context()
2026-09-13 10:53:42 +02:00
return NewClient(context.APIURL, context.Token)
}
type Client struct {
*http.Client
base string
token string
}
func (c *Client) Do(req *http.Request) (*http.Response, error) {
req.Header.Set("Authorization", c.token)
if !req.URL.IsAbs() {
u, err := url.Parse(fmt.Sprintf("%s%s", c.base, req.URL))
if err != nil {
return nil, err
}
req.URL = u
}
return c.Client.Do(req)
}
2026-09-13 10:53:42 +02:00
// HasContentType reports whether the response content-type matches the given
// media type. An empty content-type is treated as application/octet-stream.
func HasContentType(r *http.Response, mimetype string) bool {
contentType := r.Header.Get("content-type")
if contentType == "" {
return mimetype == "application/octet-stream"
}
for _, v := range strings.Split(contentType, ",") {
t, _, err := mime.ParseMediaType(v)
if err != nil {
break
}
if t == mimetype {
return true
}
}
return false
}