Files
gitea-mcp/internal/gitea/client.go
2026-05-04 22:25:10 +02:00

102 lines
2.4 KiB
Go

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)
}
type rawResponse struct {
Body []byte
Status int
Headers http.Header
}
func (c *Client) doRaw(ctx context.Context, method, path string, body []byte) (*rawResponse, 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, 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, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
return &rawResponse{Body: b, Status: resp.StatusCode, Headers: resp.Header}, err
}