congo.go

97 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
package emailers

import (
	"bytes"
	"embed"
	"encoding/json"
	"fmt"
	"html/template"
	"io"
	"net/http"

	"congo.gg/pkg/application"
)

// Congo sends emails via the Congo Email service API
type Congo struct {
	application.BaseEmailer
	baseURL string
	apiKey  string
	from    string
	client  *http.Client
}

// CongoOption configures the Congo emailer.
type CongoOption func(*Congo)

// WithCongoBaseURL sets the congo-email service URL.
func WithCongoBaseURL(url string) CongoOption {
	return func(c *Congo) { c.baseURL = url }
}

// WithCongoHTTPClient sets a custom HTTP client for the Congo emailer.
func WithCongoHTTPClient(client *http.Client) CongoOption {
	return func(c *Congo) { c.client = client }
}

// NewCongo creates a new Congo emailer that sends via email.congo.gg
//
// Example:
//
//	//go:embed all:emails
//	var emails embed.FS
//
//	emailer := emailers.NewCongo(emails, apiKey, "noreply@example.com", nil)
func NewCongo(emails embed.FS, apiKey, from string, funcs template.FuncMap, opts ...CongoOption) *Congo {
	c := &Congo{
		baseURL: "https://email.congo.gg",
		apiKey:  apiKey,
		from:    from,
		client:  http.DefaultClient,
	}
	c.Init(emails, funcs)
	for _, opt := range opts {
		opt(c)
	}
	return c
}

// Send renders a template and sends it via the Congo Email API
func (c *Congo) Send(to, subject, templateName string, data map[string]any) error {
	body, err := c.Render(templateName, data)
	if err != nil {
		return fmt.Errorf("render email: %w", err)
	}

	payload, err := json.Marshal(map[string]string{
		"to":      to,
		"subject": subject,
		"body":    body,
		"from":    c.from,
	})
	if err != nil {
		return fmt.Errorf("marshal payload: %w", err)
	}

	req, err := http.NewRequest("POST", c.baseURL+"/api/send", bytes.NewReader(payload))
	if err != nil {
		return fmt.Errorf("create request: %w", err)
	}

	req.Header.Set("Authorization", "Bearer "+c.apiKey)
	req.Header.Set("Content-Type", "application/json")

	resp, err := c.client.Do(req)
	if err != nil {
		return fmt.Errorf("send request: %w", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		var respBody bytes.Buffer
		respBody.ReadFrom(io.LimitReader(resp.Body, 1<<20))
		return fmt.Errorf("congo email API error: %s — %s", resp.Status, respBody.String())
	}

	return nil
}