feat(gitea): base http client with token auth
This commit is contained in:
69
internal/gitea/client.go
Normal file
69
internal/gitea/client.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package gitea
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
baseURL string
|
||||
token string
|
||||
hc *http.Client
|
||||
}
|
||||
|
||||
func NewClient(baseURL, token string) *Client {
|
||||
return &Client{
|
||||
baseURL: baseURL,
|
||||
token: token,
|
||||
hc: &http.Client{Timeout: 30 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) do(ctx context.Context, method, path string, body []byte) ([]byte, int, error) {
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
reader = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, c.baseURL+path, reader)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if c.token != "" {
|
||||
req.Header.Set("Authorization", "token "+c.token)
|
||||
}
|
||||
if body != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.hc.Do(req)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
b, err := io.ReadAll(resp.Body)
|
||||
return b, resp.StatusCode, err
|
||||
}
|
||||
|
||||
func (c *Client) GetJSON(ctx context.Context, path string) ([]byte, int, error) {
|
||||
return c.do(ctx, http.MethodGet, path, nil)
|
||||
}
|
||||
|
||||
func (c *Client) PostJSON(ctx context.Context, path string, body []byte) ([]byte, int, error) {
|
||||
return c.do(ctx, http.MethodPost, path, body)
|
||||
}
|
||||
|
||||
func (c *Client) PatchJSON(ctx context.Context, path string, body []byte) ([]byte, int, error) {
|
||||
return c.do(ctx, http.MethodPatch, path, body)
|
||||
}
|
||||
|
||||
func (c *Client) PutJSON(ctx context.Context, path string, body []byte) ([]byte, int, error) {
|
||||
return c.do(ctx, http.MethodPut, path, body)
|
||||
}
|
||||
|
||||
func (c *Client) DeleteJSON(ctx context.Context, path string) ([]byte, int, error) {
|
||||
return c.do(ctx, http.MethodDelete, path, nil)
|
||||
}
|
||||
Reference in New Issue
Block a user