Add client package.
This commit is contained in:
76
client/database.go
Normal file
76
client/database.go
Normal file
@@ -0,0 +1,76 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// DatabaseCredentials represents the database connection credentials.
|
||||
type DatabaseCredentials struct {
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Name string `json:"name"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
// GetDatabaseCredentials retrieves database credentials from the MCIAS server.
|
||||
// This method requires the client to be authenticated (have a valid token).
|
||||
func (c *Client) GetDatabaseCredentials(ctx context.Context) (*DatabaseCredentials, error) {
|
||||
if !c.IsAuthenticated() {
|
||||
return nil, fmt.Errorf("client is not authenticated, call LoginWithPassword or LoginWithToken first")
|
||||
}
|
||||
|
||||
if c.Username == "" {
|
||||
return nil, fmt.Errorf("username is not set, call LoginWithPassword or LoginWithToken first")
|
||||
}
|
||||
|
||||
// Build the URL with query parameters
|
||||
baseURL := fmt.Sprintf("%s/v1/database/credentials", c.BaseURL)
|
||||
params := url.Values{}
|
||||
params.Add("username", c.Username)
|
||||
requestURL := fmt.Sprintf("%s?%s", baseURL, params.Encode())
|
||||
|
||||
// Create the request
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", requestURL, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create request: %w", err)
|
||||
}
|
||||
|
||||
// Add authorization header
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.Token))
|
||||
|
||||
// Send the request
|
||||
resp, err := c.HTTPClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to send request: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// Read the response body
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response: %w", err)
|
||||
}
|
||||
|
||||
// Check for errors
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
var errResp ErrorResponse
|
||||
if unmarshalErr := json.Unmarshal(body, &errResp); unmarshalErr == nil {
|
||||
return nil, fmt.Errorf("API error: %s (code: %s)", errResp.Error, errResp.ErrorCode)
|
||||
}
|
||||
return nil, fmt.Errorf("API error: %s", resp.Status)
|
||||
}
|
||||
|
||||
// Parse the response
|
||||
var creds DatabaseCredentials
|
||||
if err := json.Unmarshal(body, &creds); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse response: %w", err)
|
||||
}
|
||||
|
||||
return &creds, nil
|
||||
}
|
||||
Reference in New Issue
Block a user