84 lines
2.0 KiB
Go
84 lines
2.0 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"net/url"
|
|
"time"
|
|
)
|
|
|
|
// client is a minimal typed HTTP client for the messenger API.
|
|
type client struct {
|
|
base string
|
|
http *http.Client
|
|
}
|
|
|
|
func newClient(baseURL string) *client {
|
|
return &client{base: baseURL, http: &http.Client{Timeout: 10 * time.Second}}
|
|
}
|
|
|
|
func (c *client) post(path, token string, body, out any) error {
|
|
raw, err := json.Marshal(body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req, err := http.NewRequest(http.MethodPost, c.base+path, bytes.NewReader(raw))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
return c.do(req, token, http.StatusCreated, out)
|
|
}
|
|
|
|
// login opens a session with Basic credentials and returns its bearer token.
|
|
func (c *client) login(username, password string) (string, error) {
|
|
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
req.SetBasicAuth(username, password)
|
|
var session struct {
|
|
Token string `json:"token"`
|
|
}
|
|
if err := c.do(req, "", http.StatusCreated, &session); err != nil {
|
|
return "", err
|
|
}
|
|
return session.Token, nil
|
|
}
|
|
|
|
// get requests the largest page the contract allows, continuing from cursor
|
|
// when it is set.
|
|
func (c *client) get(path, token, cursor string, out any) error {
|
|
query := url.Values{"limit": {"100"}}
|
|
if cursor != "" {
|
|
query.Set("cursor", cursor)
|
|
}
|
|
req, err := http.NewRequest(http.MethodGet, c.base+path+"?"+query.Encode(), nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return c.do(req, token, http.StatusOK, out)
|
|
}
|
|
|
|
func (c *client) do(req *http.Request, token string, want int, out any) error {
|
|
if token != "" {
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
|
}
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer resp.Body.Close()
|
|
payload, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if resp.StatusCode != want {
|
|
return fmt.Errorf("%s %s: status %d, want %d: %s", req.Method, req.URL.Path, resp.StatusCode, want, payload)
|
|
}
|
|
return json.Unmarshal(payload, out)
|
|
}
|