-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
lemmy.go
181 lines (156 loc) · 3.86 KB
/
lemmy.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
package lemmy
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"github.com/google/go-querystring/query"
)
// ErrNoToken is an error returned by ClientLogin if the server sends a null or empty token
var ErrNoToken = errors.New("the server didn't provide a token value in its response")
// Client is a client for Lemmy's HTTP API
type Client struct {
client *http.Client
baseURL *url.URL
Token string
}
// New creates a new Lemmy client with the default HTTP client.
func New(baseURL string) (*Client, error) {
return NewWithClient(baseURL, http.DefaultClient)
}
// NewWithClient creates a new Lemmy client with the given HTTP client
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
}
// 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)
if err != nil {
return err
}
token, ok := lr.JWT.Value()
if !ok || token == "" {
return ErrNoToken
}
c.Token = token
return nil
}
// req makes a request to the server
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")
if c.Token != "" {
req.Header.Add("Authorization", "Bearer "+c.Token)
}
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
}
// getReq makes a get request to the Lemmy server.
// It's separate from req() because it uses query
// parameters rather than a JSON request body.
func (c *Client) getReq(ctx context.Context, method string, path string, data, resp any) (*http.Response, error) {
getURL := c.baseURL.JoinPath(path)
if data != nil {
vals, err := query.Values(data)
if err != nil {
return nil, err
}
getURL.RawQuery = vals.Encode()
}
req, err := http.NewRequestWithContext(
ctx,
method,
getURL.String(),
nil,
)
if err != nil {
return nil, err
}
if c.Token != "" {
req.Header.Add("Authorization", "Bearer "+c.Token)
}
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
}
// 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))
}
}
// emptyResponse is a response without any fields.
// It has an Error field to capture any errors.
type emptyResponse struct {
Error Optional[string] `json:"error"`
}
// resError checks if the response contains an error, and if so, returns
// a Go error representing it.
func resError(res *http.Response, err Optional[string]) error {
if errstr, ok := err.Value(); ok {
return Error{
Code: res.StatusCode,
ErrStr: errstr,
}
} else if res.StatusCode != http.StatusOK {
return Error{
Code: res.StatusCode,
}
} else {
return nil
}
}