mailcow-admin-aliases/internal/mailcow/domains.go

61 lines
1.5 KiB
Go
Raw Normal View History

2024-07-24 17:36:01 +02:00
package mailcow
import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
2024-07-26 12:16:59 +02:00
"os"
2024-07-24 17:36:01 +02:00
"time"
"code.lila.network/adoralaura/mailcow-admin-aliases/internal/configuration"
)
type MailcowDomain struct {
DomainName string `json:"domain_name"`
}
func LoadDomains(cfg configuration.Config) ([]MailcowDomain, error) {
var domains []MailcowDomain
url := cfg.ApiEndpoint + configuration.AllDomainsApiEndpoint
method := "GET"
client := &http.Client{Timeout: 10 * time.Second}
req, err := http.NewRequest(method, url, nil)
slog.Debug("domain request", "method", method, "url", url)
if err != nil {
return []MailcowDomain{}, fmt.Errorf("failed to create http request: %w", err)
}
req.Header.Add("accept", "application/json")
req.Header.Add("X-API-Key", cfg.ApiKey)
res, err := client.Do(req)
if err != nil {
return []MailcowDomain{}, fmt.Errorf("failed to request domains from server: %w", err)
}
defer res.Body.Close()
2024-07-26 12:16:59 +02:00
if res.StatusCode != 200 {
slog.Error("API request unsuccessful", "status", res.Status, "status-code", res.StatusCode)
os.Exit(1)
}
2024-07-24 17:36:01 +02:00
slog.Debug("domain response received", "status", res.Status, "status-code", res.StatusCode)
body, err := io.ReadAll(res.Body)
if err != nil {
return []MailcowDomain{}, fmt.Errorf("failed to read domain request body: %w", err)
}
err = json.Unmarshal(body, &domains)
if err != nil {
return []MailcowDomain{}, fmt.Errorf("failed to unmarshal domain request body: %w", err)
}
return domains, nil
}