75 lines
1.7 KiB
Go
75 lines
1.7 KiB
Go
// Package pluralkit is a binding to the PluralKit API as documented here: https://pluralkit.me/api
|
|
package pluralkit
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"io"
|
|
"net/http"
|
|
|
|
"within.website/x/web"
|
|
)
|
|
|
|
// Client connects to the PluralKit API.
|
|
type Client struct {
|
|
baseURL string
|
|
token string
|
|
hc *http.Client
|
|
}
|
|
|
|
// RoundTrip sends an authenticated request to the PluralKit API.
|
|
func (c Client) RoundTrip(req *http.Request) (*http.Response, error) {
|
|
req.Header.Set("Authorization", c.token)
|
|
return c.hc.Do(req)
|
|
}
|
|
|
|
// Do is a high level wrapper for sending data to/from the PluralKit API.
|
|
func (c Client) Do(method, pathNoSlash string, want int, post interface{}, result interface{}) error {
|
|
var body io.Reader
|
|
if post != nil {
|
|
var buf bytes.Buffer
|
|
err := json.NewEncoder(&buf).Encode(post)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
body = &buf
|
|
}
|
|
req := c.MakeRequest(method, pathNoSlash, body)
|
|
resp, err := c.RoundTrip(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if resp.StatusCode != want {
|
|
return web.NewError(want, resp)
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
err = json.NewDecoder(resp.Body).Decode(result)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// MakeRequest makes a HTTP request for the PluralKit API, catting pathNoSlash to the base PluralKit API address.
|
|
func (c Client) MakeRequest(method, pathNoSlash string, body io.Reader) *http.Request {
|
|
req, err := http.NewRequest(method, c.baseURL+pathNoSlash, body)
|
|
if err != nil /* programmer error */ {
|
|
panic(err)
|
|
}
|
|
|
|
return req
|
|
}
|
|
|
|
// New creates a new instance of the PluralKit API client.
|
|
func New(token string, hc *http.Client) Client {
|
|
return Client{
|
|
baseURL: "https://api.pluralkit.me/v1/",
|
|
token: token,
|
|
hc: hc,
|
|
}
|
|
}
|