terraform-provider-edge-con.../internal/client/client.go
2025-11-11 14:15:52 +01:00

81 lines
1.8 KiB
Go

package client
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)
// Client is the API client for Edge Connect
type Client struct {
BaseURL string
HTTPClient *http.Client
Token string
Username string
Password string
}
// NewClient creates a new Edge Connect API client
func NewClient(baseURL, token, username, password string) *Client {
return &Client{
BaseURL: baseURL,
HTTPClient: &http.Client{
Timeout: time.Second * 30,
},
Token: token,
Username: username,
Password: password,
}
}
// doRequest performs an HTTP request with authentication
func (c *Client) doRequest(method, path string, body interface{}) ([]byte, error) {
var reqBody io.Reader
if body != nil {
jsonBody, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("failed to marshal request body: %w", err)
}
reqBody = bytes.NewBuffer(jsonBody)
}
req, err := http.NewRequest(method, c.BaseURL+path, reqBody)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
// Add authentication
if c.Token != "" {
req.Header.Set("Authorization", "Bearer "+c.Token)
} else if c.Username != "" && c.Password != "" {
req.SetBasicAuth(c.Username, c.Password)
}
resp, err := c.HTTPClient.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response body: %w", err)
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(respBody))
}
return respBody, nil
}
// HealthCheck performs a health check on the API
func (c *Client) HealthCheck() error {
_, err := c.doRequest("GET", "/api/v1/", nil)
return err
}