all repos

onasty @ dependabot/github_actions/marocchino/tool-versions-action-2

a one-time notes service

onasty/mailer/handlers.go (view raw)

Smirnov Oleksandr Smirnov Oleksandr
ss2316544@gmail.com
feat: mailer service (#55)..., 1 year ago
1
package main
2
3
import (
4
	"context"
5
	"encoding/json"
6
	"log/slog"
7
	"time"
8
9
	"github.com/nats-io/nats.go/micro"
10
	"github.com/olexsmir/onasty/internal/transport/http/reqid"
11
)
12
13
type Handlers struct {
14
	service *Service
15
}
16
17
func NewHandlers(service *Service) *Handlers {
18
	return &Handlers{
19
		service: service,
20
	}
21
}
22
23
func (h Handlers) RegisterAll(svc micro.Service) error {
24
	m := svc.AddGroup("mailer")
25
	if err := m.AddEndpoint("ping", micro.HandlerFunc(h.pingHandler)); err != nil {
26
		return err
27
	}
28
29
	if err := m.AddEndpoint("send", micro.HandlerFunc(h.sendHandler)); err != nil {
30
		return err
31
	}
32
33
	return nil
34
}
35
36
type pingResponse struct {
37
	Message string `json:"message"`
38
}
39
40
func (h Handlers) pingHandler(req micro.Request) {
41
	_ = req.RespondJSON(pingResponse{
42
		Message: "pong",
43
	})
44
}
45
46
type sendRequest struct {
47
	RequestID string `json:"request_id"`
48
49
	Receiver     string            `json:"receiver"`
50
	TemplateName string            `json:"template_name"`
51
	Options      map[string]string `json:"options"`
52
}
53
54
func (h Handlers) sendHandler(req micro.Request) {
55
	var inp sendRequest
56
	if err := json.Unmarshal(req.Data(), &inp); err != nil {
57
		slog.Error("failed to unmarshal input data", "err", err)
58
		return
59
	}
60
61
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
62
	ctx = reqid.SetContext(ctx, inp.RequestID)
63
64
	if err := h.service.Send(ctx, cancel, inp.Receiver, inp.TemplateName, inp.Options); err != nil {
65
		_ = req.Error("500", err.Error(), nil)
66
	}
67
68
	_ = req.Respond(nil)
69
}