mailcow-admin-aliases/internal/mailcow/domains.go
Adora Laura Kalb 8cf8c7871b
All checks were successful
ci/woodpecker/tag/build-and-deploy/1 Pipeline was successful
ci/woodpecker/tag/build-and-deploy/2 Pipeline was successful
fix api error response handling
2024-07-26 12:16:59 +02:00

60 lines
1.5 KiB
Go

package mailcow
import (
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"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()
if res.StatusCode != 200 {
slog.Error("API request unsuccessful", "status", res.Status, "status-code", res.StatusCode)
os.Exit(1)
}
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
}