feat: basic initial support for actions

This commit is contained in:
Romain Bertrand 2025-12-08 11:16:35 +01:00
parent 69bbbfc51b
commit ca17526594
4 changed files with 767 additions and 20 deletions

View file

@ -1,6 +1,11 @@
package api
import (
"encoding/json"
"fmt"
"io"
"net/http"
"code.gitea.io/sdk/gitea"
"codeberg.org/romaintb/fgj/internal/config"
)
@ -8,6 +13,7 @@ import (
type Client struct {
*gitea.Client
hostname string
token string
}
func NewClient(hostname, token string) (*Client, error) {
@ -23,6 +29,7 @@ func NewClient(hostname, token string) (*Client, error) {
return &Client{
Client: client,
hostname: hostname,
token: token,
}, nil
}
@ -38,3 +45,42 @@ func NewClientFromConfig(cfg *config.Config, hostname string) (*Client, error) {
func (c *Client) Hostname() string {
return c.hostname
}
// GetJSON performs a GET request to the specified path and decodes the JSON response
func (c *Client) GetJSON(path string, result any) error {
baseURL := "https://" + c.hostname
url := baseURL + path
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
// Set authentication header
if c.token != "" {
req.Header.Set("Authorization", "token "+c.token)
}
req.Header.Set("Accept", "application/json")
httpClient := &http.Client{}
resp, err := httpClient.Do(req)
if err != nil {
return fmt.Errorf("failed to perform request: %w", err)
}
defer func() {
if closeErr := resp.Body.Close(); closeErr != nil && err == nil {
err = fmt.Errorf("failed to close response body: %w", closeErr)
}
}()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return fmt.Errorf("failed to decode response: %w", err)
}
return nil
}