-
Notifications
You must be signed in to change notification settings - Fork 15
/
app.go
104 lines (84 loc) · 2.23 KB
/
app.go
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
98
99
100
101
102
103
104
package caddynats
import (
"encoding/json"
"fmt"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/nats-io/jsm.go/natscontext"
"github.com/nats-io/nats.go"
"go.uber.org/zap"
)
func init() {
caddy.RegisterModule(App{})
}
// App connects caddy to a NATS server.
//
// NATS is a simple, secure and performant communications system for digital
// systems, services and devices.
type App struct {
Context string `json:"context,omitempty"`
HandlersRaw []json.RawMessage `json:"handle,omitempty" caddy:"namespace=nats.handlers inline_key=handler"`
// Decoded values
Handlers []Handler `json:"-"`
conn *nats.Conn
logger *zap.Logger
ctx caddy.Context
}
// CaddyModule returns the Caddy module information.
func (App) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "nats",
New: func() caddy.Module { return new(App) },
}
}
// Provision sets up the app
func (app *App) Provision(ctx caddy.Context) error {
// Set logger and Context
app.ctx = ctx
app.logger = ctx.Logger(app)
// Set up handlers
if app.HandlersRaw != nil {
vals, err := ctx.LoadModule(app, "HandlersRaw")
if err != nil {
return fmt.Errorf("loading handler modules: %v", err)
}
for _, val := range vals.([]interface{}) {
app.Handlers = append(app.Handlers, val.(Handler))
}
}
return nil
}
func (app *App) Start() error {
// Connect to the NATS server
app.logger.Info("connecting via NATS context", zap.String("context", app.Context))
conn, err := natscontext.Connect(app.Context)
if err != nil {
return err
}
app.logger.Info("connected to NATS server", zap.String("url", conn.ConnectedUrlRedacted()))
app.conn = conn
for _, handler := range app.Handlers {
err := handler.Subscribe(conn)
if err != nil {
return err
}
}
return nil
}
func (app *App) Stop() error {
defer app.conn.Close()
app.logger.Info("closing NATS connection", zap.String("url", app.conn.ConnectedUrlRedacted()))
for _, handler := range app.Handlers {
err := handler.Unsubscribe(app.conn)
if err != nil {
return err
}
}
return nil
}
// Interface guards
var (
_ caddy.App = (*App)(nil)
_ caddy.Provisioner = (*App)(nil)
_ caddyfile.Unmarshaler = (*App)(nil)
)