package hetzner import ( "fmt" ) type SSHKey struct { ID int `json:"id"` Name string `json:"name"` Fingerprint string `json:"fingerprint"` PublicKey string `json:"public_key"` Labels map[string]string `json:"labels,omitempty"` } type SSHKeyResponse struct { SSHKey SSHKey `json:"ssh_key"` } type SSHKeysResponse struct { SSHKeys []SSHKey `json:"ssh_keys"` } type CreateSSHKeyRequest struct { Name string `json:"name"` PublicKey string `json:"public_key"` Labels map[string]string `json:"labels,omitempty"` } func (c *Client) CreateSSHKey(name, publicKey string) (*SSHKey, error) { req := CreateSSHKeyRequest{ Name: name, PublicKey: publicKey, Labels: map[string]string{ "managed-by": "sslh-lab", }, } var resp SSHKeyResponse httpResp, err := c.resty.R(). SetBody(req). SetResult(&resp). Post("/ssh_keys") if err != nil { return nil, fmt.Errorf("failed to create SSH key: %w", err) } if httpResp.IsError() { return nil, fmt.Errorf("API error: %s - %s", httpResp.Status(), string(httpResp.Body())) } return &resp.SSHKey, nil } func (c *Client) GetSSHKeyByName(name string) (*SSHKey, error) { var resp SSHKeysResponse httpResp, err := c.resty.R(). SetResult(&resp). Get("/ssh_keys") if err != nil { return nil, fmt.Errorf("failed to list SSH keys: %w", err) } if httpResp.IsError() { return nil, fmt.Errorf("API error: %s - %s", httpResp.Status(), string(httpResp.Body())) } for _, key := range resp.SSHKeys { if key.Name == name { return &key, nil } } return nil, fmt.Errorf("SSH key with name '%s' not found", name) } func (c *Client) GetOrCreateSSHKey(name, publicKey string) (int, error) { existingKey, err := c.GetSSHKeyByName(name) if err == nil { return existingKey.ID, nil } newKey, err := c.CreateSSHKey(name, publicKey) if err != nil { return 0, fmt.Errorf("failed to create SSH key: %w", err) } return newKey.ID, nil } func (c *Client) DeleteSSHKey(keyID int) error { httpResp, err := c.resty.R(). Delete(fmt.Sprintf("/ssh_keys/%d", keyID)) if err != nil { return fmt.Errorf("failed to delete SSH key: %w", err) } if httpResp.IsError() { return fmt.Errorf("API error: %s - %s", httpResp.Status(), string(httpResp.Body())) } return nil }