1
0
mirror of https://github.com/mrusme/neonmodem.git synced 2024-12-04 14:46:37 -05:00
neonmodem/system/discourse/api/client.go

217 lines
4.1 KiB
Go
Raw Normal View History

package api
2022-12-29 22:03:38 -05:00
2023-01-08 22:07:35 -05:00
// https://docs.discourse.org
2022-12-29 22:03:38 -05:00
import (
"bytes"
"context"
"encoding/json"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strings"
2023-01-10 18:56:02 -05:00
"time"
2022-12-29 22:03:38 -05:00
"github.com/hashicorp/go-retryablehttp"
)
type RequestError struct {
Err error
2022-12-29 22:03:38 -05:00
}
func (re *RequestError) Error() string {
return re.Err.Error()
}
type Logger interface {
Debug(args ...interface{})
Debugf(format string, args ...interface{})
Info(args ...interface{})
Infof(format string, args ...interface{})
Warn(args ...interface{})
Warnf(format string, args ...interface{})
Error(args ...interface{})
Errorf(format string, args ...interface{})
Fatal(args ...interface{})
Fatalf(format string, args ...interface{})
}
type StdLogger struct {
L Logger
}
func NewStdLogger(l Logger) retryablehttp.Logger {
return &StdLogger{
L: l,
}
}
func (l *StdLogger) Printf(message string, v ...interface{}) {
l.L.Debug(message, v)
}
type ClientConfig struct {
Endpoint string
Credentials map[string]string
HTTPClient *http.Client
Logger Logger
}
type Client struct {
httpClient *retryablehttp.Client
endpoint *url.URL
credentials map[string]string
logger Logger
2022-12-30 23:57:03 -05:00
Posts PostsService
Topics TopicsService
Categories CategoriesService
2022-12-29 22:03:38 -05:00
}
func NewDefaultClientConfig(
endpoint string,
2023-01-10 18:56:02 -05:00
proxy string,
2022-12-29 22:03:38 -05:00
credentials map[string]string,
logger Logger,
) ClientConfig {
2023-01-10 18:56:02 -05:00
var httpClient *http.Client = nil
var httpTransport *http.Transport = nil
if proxy != "" {
proxyURL, err := url.Parse(proxy)
if err != nil {
logger.Error(err)
} else {
logger.Debugf("setting up http proxy transport: %s\n", proxyURL.String())
httpTransport = &http.Transport{
Proxy: http.ProxyURL(proxyURL),
}
}
}
httpClient = &http.Client{
Transport: httpTransport,
Timeout: time.Second * 10,
}
2022-12-29 22:03:38 -05:00
return ClientConfig{
Endpoint: endpoint,
Credentials: credentials,
2023-01-10 18:56:02 -05:00
HTTPClient: httpClient,
2022-12-29 22:03:38 -05:00
Logger: logger,
}
}
func NewClient(cc *ClientConfig) *Client {
c := new(Client)
c.logger = cc.Logger
c.httpClient = retryablehttp.NewClient()
c.httpClient.RetryMax = 3
if c.logger != nil {
c.httpClient.Logger = NewStdLogger(c.logger)
}
c.httpClient.HTTPClient = cc.HTTPClient
c.endpoint, _ = url.Parse(cc.Endpoint)
c.credentials = cc.Credentials
c.Posts = &PostServiceHandler{client: c}
c.Topics = &TopicServiceHandler{client: c}
2022-12-30 23:57:03 -05:00
c.Categories = &CategoryServiceHandler{client: c}
2022-12-29 22:03:38 -05:00
return c
}
func (c *Client) NewRequest(
ctx context.Context,
method string,
location string,
body interface{},
) (*http.Request, error) {
var parsedURL *url.URL
var req *http.Request
var err error
if parsedURL, err = c.endpoint.Parse(location); err != nil {
return nil, err
}
buffer := new(bytes.Buffer)
if body != nil {
if err = json.NewEncoder(buffer).Encode(body); err != nil {
return nil, err
}
}
if req, err = http.NewRequest(
method,
parsedURL.String(),
buffer,
); err != nil {
return nil, err
}
req.Header.Add("User-Agent", "Neon Modem Overdrive")
2022-12-29 22:03:38 -05:00
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Api-Client-Id", c.credentials["client_id"])
req.Header.Add("User-Api-Key", c.credentials["key"])
2022-12-29 22:03:38 -05:00
return req, nil
}
type ErrorBody struct {
Errors []string `json:"errors"`
}
2022-12-29 22:03:38 -05:00
func (c *Client) Do(
ctx context.Context,
req *http.Request,
content interface{},
2022-12-29 22:03:38 -05:00
) error {
var rreq *retryablehttp.Request
var res *http.Response
var body []byte
var err error
if rreq, err = retryablehttp.FromRequest(req); err != nil {
return err
}
rreq = rreq.WithContext(ctx)
if res, err = c.httpClient.Do(rreq); err != nil {
return err
}
defer res.Body.Close()
if body, err = ioutil.ReadAll(res.Body); err != nil {
return err
}
if content != nil {
if err = json.Unmarshal(body, content); err != nil {
return err
}
}
if res.StatusCode < http.StatusOK ||
res.StatusCode > http.StatusNoContent {
var errbody ErrorBody
if err := json.Unmarshal(body, &errbody); err == nil {
return &RequestError{
Err: errors.New(strings.Join(errbody.Errors, "\n")),
}
}
2022-12-29 22:03:38 -05:00
return &RequestError{
Err: errors.New(string(body)),
2022-12-29 22:03:38 -05:00
}
}
return nil
}