All checks were successful
default / ensure tests work (push) Successful in 27s
62 lines
1.3 KiB
Go
62 lines
1.3 KiB
Go
package sdk
|
|
|
|
import (
|
|
"fmt"
|
|
"mime"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
)
|
|
|
|
// 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 {
|
|
context := a.Context()
|
|
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)
|
|
}
|
|
|
|
// 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
|
|
}
|