go-lemmy/lemmy.go

182 lines
3.9 KiB
Go
Raw Normal View History

2022-12-10 17:17:16 +00:00
package lemmy
import (
"bytes"
"context"
"encoding/json"
2023-10-05 00:13:27 +00:00
"errors"
2023-10-05 04:08:55 +00:00
"fmt"
2022-12-10 17:17:16 +00:00
"io"
"net/http"
"net/url"
"github.com/google/go-querystring/query"
)
2023-10-05 00:14:28 +00:00
// ErrNoToken is an error returned by ClientLogin if the server sends a null or empty token
2023-10-05 00:13:27 +00:00
var ErrNoToken = errors.New("the server didn't provide a token value in its response")
2022-12-13 18:49:58 +00:00
// Client is a client for Lemmy's HTTP API
2022-12-10 17:17:16 +00:00
type Client struct {
client *http.Client
baseURL *url.URL
2022-12-13 18:49:58 +00:00
Token string
2022-12-10 17:17:16 +00:00
}
2022-12-13 18:49:58 +00:00
// New creates a new Lemmy client with the default HTTP client.
2022-12-10 17:17:16 +00:00
func New(baseURL string) (*Client, error) {
return NewWithClient(baseURL, http.DefaultClient)
}
2022-12-13 18:49:58 +00:00
// NewWithClient creates a new Lemmy client with the given HTTP client
2022-12-10 17:17:16 +00:00
func NewWithClient(baseURL string, client *http.Client) (*Client, error) {
u, err := url.Parse(baseURL)
if err != nil {
return nil, err
}
u = u.JoinPath("/api/v3")
return &Client{baseURL: u, client: client}, nil
}
2023-10-05 04:13:20 +00:00
// ClientLogin logs in to Lemmy by calling the login endpoint, and
// stores the returned token in the Token field for use in future requests.
//
// The Token field can be set manually if you'd like to persist the
// token somewhere.
func (c *Client) ClientLogin(ctx context.Context, data Login) error {
lr, err := c.Login(ctx, data)
2022-12-10 17:17:16 +00:00
if err != nil {
return err
}
2023-10-05 00:13:27 +00:00
token, ok := lr.JWT.Value()
if !ok || token == "" {
return ErrNoToken
}
c.Token = token
2022-12-10 17:17:16 +00:00
return nil
}
2022-12-13 18:49:58 +00:00
// req makes a request to the server
2022-12-10 17:17:16 +00:00
func (c *Client) req(ctx context.Context, method string, path string, data, resp any) (*http.Response, error) {
var r io.Reader
if data != nil {
jsonData, err := json.Marshal(data)
if err != nil {
return nil, err
}
r = bytes.NewReader(jsonData)
}
req, err := http.NewRequestWithContext(
ctx,
method,
c.baseURL.JoinPath(path).String(),
r,
)
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/json")
2023-10-04 23:16:36 +00:00
if c.Token != "" {
req.Header.Add("Authorization", "Bearer "+c.Token)
}
2022-12-10 17:17:16 +00:00
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(resp)
if err == io.EOF {
return res, nil
} else if err != nil {
return nil, err
}
return res, nil
}
2022-12-13 18:49:58 +00:00
// getReq makes a get request to the Lemmy server.
// It's separate from req() because it uses query
2022-12-13 18:49:58 +00:00
// parameters rather than a JSON request body.
2022-12-10 17:17:16 +00:00
func (c *Client) getReq(ctx context.Context, method string, path string, data, resp any) (*http.Response, error) {
getURL := c.baseURL.JoinPath(path)
2023-10-04 23:16:36 +00:00
if data != nil {
vals, err := query.Values(data)
if err != nil {
return nil, err
}
getURL.RawQuery = vals.Encode()
2022-12-10 17:17:16 +00:00
}
req, err := http.NewRequestWithContext(
ctx,
method,
getURL.String(),
nil,
)
if err != nil {
return nil, err
}
2023-10-04 23:16:36 +00:00
if c.Token != "" {
req.Header.Add("Authorization", "Bearer "+c.Token)
}
2022-12-10 17:17:16 +00:00
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
err = json.NewDecoder(res.Body).Decode(resp)
if err == io.EOF {
return res, nil
} else if err != nil {
return nil, err
}
return res, nil
}
2023-10-05 04:08:55 +00:00
// Error represents an error returned by the Lemmy API
type Error struct {
ErrStr string
Code int
}
func (le Error) Error() string {
if le.ErrStr != "" {
return fmt.Sprintf("%d %s: %s", le.Code, http.StatusText(le.Code), le.ErrStr)
} else {
return fmt.Sprintf("%d %s", le.Code, http.StatusText(le.Code))
}
}
2023-10-05 03:45:36 +00:00
// emptyResponse is a response without any fields.
// It has an Error field to capture any errors.
type emptyResponse struct {
Error Optional[string] `json:"error"`
}
2023-10-05 04:13:20 +00:00
// resError checks if the response contains an error, and if so, returns
// a Go error representing it.
2023-10-05 03:45:36 +00:00
func resError(res *http.Response, err Optional[string]) error {
if errstr, ok := err.Value(); ok {
return Error{
2022-12-10 17:17:16 +00:00
Code: res.StatusCode,
2023-10-05 03:45:36 +00:00
ErrStr: errstr,
2022-12-10 17:17:16 +00:00
}
} else if res.StatusCode != http.StatusOK {
2023-10-05 04:08:55 +00:00
return Error{
2022-12-10 17:17:16 +00:00
Code: res.StatusCode,
}
} else {
return nil
}
}