NewClient creates a new Proxmox API client with dependency injection.
(config interfaces.Config, options ...ClientOption)
| 675 | |
| 676 | // NewClient creates a new Proxmox API client with dependency injection. |
| 677 | func NewClient(config interfaces.Config, options ...ClientOption) (*Client, error) { |
| 678 | // Apply options |
| 679 | opts := defaultOptions() |
| 680 | for _, option := range options { |
| 681 | option(opts) |
| 682 | } |
| 683 | |
| 684 | // Validate input parameters |
| 685 | if config.GetAddr() == "" { |
| 686 | return nil, fmt.Errorf("proxmox address cannot be empty") |
| 687 | } |
| 688 | |
| 689 | // Construct base URL - remove any API path suffix |
| 690 | baseURL := strings.TrimRight(config.GetAddr(), "/") |
| 691 | if !strings.HasPrefix(baseURL, "https://") && !strings.HasPrefix(baseURL, "http://") { |
| 692 | baseURL = "https://" + baseURL |
| 693 | } |
| 694 | |
| 695 | // Remove /api2/json suffix if present to get the server base URL |
| 696 | serverBaseURL := strings.TrimSuffix(baseURL, "/api2/json") |
| 697 | |
| 698 | opts.Logger.Debug("Proxmox server URL: %s", serverBaseURL) |
| 699 | opts.Logger.Debug("Proxmox API base URL: %s", serverBaseURL+"/api2/json") |
| 700 | |
| 701 | // Configure TLS |
| 702 | tlsConfig := &tls.Config{InsecureSkipVerify: config.GetInsecure()} |
| 703 | |
| 704 | transport, ok := http.DefaultTransport.(*http.Transport) |
| 705 | if !ok { |
| 706 | return nil, fmt.Errorf("failed to get default transport") |
| 707 | } |
| 708 | |
| 709 | transport = transport.Clone() |
| 710 | transport.TLSClientConfig = tlsConfig |
| 711 | |
| 712 | // Create HTTP client |
| 713 | httpClient := &http.Client{ |
| 714 | Transport: transport, |
| 715 | Timeout: 30 * time.Second, |
| 716 | } |
| 717 | |
| 718 | // Validate port presence |
| 719 | if !strings.Contains(serverBaseURL, ":") { |
| 720 | return nil, fmt.Errorf("missing port in address %s", serverBaseURL) |
| 721 | } |
| 722 | |
| 723 | // Format credentials with realm |
| 724 | userWithRealm := fmt.Sprintf("%s@%s", config.GetUser(), config.GetRealm()) |
| 725 | |
| 726 | // Create HTTP client wrapper |
| 727 | httpClientWrapper := NewHTTPClient(httpClient, serverBaseURL+"/api2/json", opts.Logger) |
| 728 | |
| 729 | // Create auth manager |
| 730 | var authManager *AuthManager |
| 731 | if config.IsUsingTokenAuth() { |
| 732 | authManager = NewAuthManagerWithToken(httpClientWrapper, config.GetAPIToken(), opts.Logger) |
| 733 | } else { |
| 734 | authManager = NewAuthManagerWithPassword(httpClientWrapper, userWithRealm, config.GetPassword(), opts.Logger) |