refactor: enhance NewClient to support environment variable fallback and add tests

This commit is contained in:
2026-05-10 11:02:34 +02:00
parent 9b040dfc7b
commit f2a15c69aa
4 changed files with 148 additions and 29 deletions
+48 -3
View File
@@ -5,6 +5,8 @@ import (
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)
@@ -24,8 +26,51 @@ type DNSRecord struct {
Value string `json:"value"`
}
// NewClient constructs a Client. host should be the bare hostname (e.g. "box.example.com").
func NewClient(host, username, password string) *Client {
// NewClient constructs a Client. Any empty parameter is filled from environment variables:
//
// host: MIAB_HOST or hostname parsed from MAILINABOX_BASE_URL
// username: MIAB_USERNAME or MAILINABOX_EMAIL
// password: MIAB_PASSWORD or MAILINABOX_PASSWORD
//
// Returns an error if a value is still empty after the env lookup.
func NewClient(host, username, password string) (*Client, error) {
if host == "" {
host = os.Getenv("MIAB_HOST")
if host == "" {
if base := os.Getenv("MAILINABOX_BASE_URL"); base != "" {
if u, err := url.Parse(base); err == nil {
host = u.Hostname()
}
}
}
}
if username == "" {
username = os.Getenv("MIAB_USERNAME")
if username == "" {
username = os.Getenv("MAILINABOX_EMAIL")
}
}
if password == "" {
password = os.Getenv("MIAB_PASSWORD")
if password == "" {
password = os.Getenv("MAILINABOX_PASSWORD")
}
}
var missing []string
if host == "" {
missing = append(missing, "MIAB_HOST or MAILINABOX_BASE_URL")
}
if username == "" {
missing = append(missing, "MIAB_USERNAME or MAILINABOX_EMAIL")
}
if password == "" {
missing = append(missing, "MIAB_PASSWORD or MAILINABOX_PASSWORD")
}
if len(missing) > 0 {
return nil, fmt.Errorf("miab: missing required environment variables: %v", missing)
}
return &Client{
host: host,
username: username,
@@ -33,7 +78,7 @@ func NewClient(host, username, password string) *Client {
httpClient: &http.Client{
Timeout: 30 * time.Second,
},
}
}, nil
}
// SetRecord replaces all existing records of the given type for name with value (HTTP PUT).