initial commit
This commit is contained in:
@@ -0,0 +1,61 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/carlmjohnson/requests"
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
baseURL string
|
||||
inner http.Client
|
||||
}
|
||||
|
||||
func NewClient(baseURL, username, password string) (*Client, error) {
|
||||
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := Client{
|
||||
baseURL: baseURL,
|
||||
inner: http.Client{
|
||||
Timeout: time.Second * 10,
|
||||
Jar: jar,
|
||||
},
|
||||
}
|
||||
if err := c.login(username, password); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func (c *Client) reqBuilder() *requests.Builder {
|
||||
return requests.
|
||||
URL(c.baseURL).
|
||||
Client(&c.inner).
|
||||
AddValidator(requests.ValidatorHandler(requests.DefaultValidator, requests.ResponseHandler(func(r *http.Response) error {
|
||||
var buf strings.Builder
|
||||
_, _ = io.Copy(&buf, r.Body)
|
||||
return fmt.Errorf("response body: %v", buf.String())
|
||||
})))
|
||||
}
|
||||
|
||||
func (c *Client) login(username, password string) error {
|
||||
err := c.reqBuilder().
|
||||
Path("/api/v2/auth/login").
|
||||
Header("Referer", c.baseURL).
|
||||
BodyForm(url.Values{"username": []string{username}, "password": []string{password}}).
|
||||
Fetch(context.TODO())
|
||||
if err != nil {
|
||||
return fmt.Errorf("login: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user