mailcow-admin-aliases/internal/mailcow/domains.go
2024-07-24 17:36:01 +02:00

54 lines
1.3 KiB
Go

package mailcow
import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"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()
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
}