-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathpublish.go
100 lines (77 loc) · 2.31 KB
/
publish.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
package caddynats
import (
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/nats-io/nats.go"
"go.uber.org/zap"
)
const publishDefaultTimeout = 10000
func init() {
caddy.RegisterModule(Publish{})
}
type Publish struct {
Subject string `json:"subject,omitempty"`
WithReply bool `json:"with_reply,omitempty"`
Timeout int64 `json:"timeout,omitempty"`
logger *zap.Logger
app *App
}
func (Publish) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.nats_publish",
New: func() caddy.Module { return new(Publish) },
}
}
func (p *Publish) Provision(ctx caddy.Context) error {
p.logger = ctx.Logger(p)
natsAppIface, err := ctx.App("nats")
if err != nil {
return fmt.Errorf("getting NATS app: %v. Make sure NATS is configured in global options", err)
}
p.app = natsAppIface.(*App)
return nil
}
func (p Publish) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
addNATSPublishVarsToReplacer(repl, r)
//TODO: What method is best here? ReplaceAll vs ReplaceWithErr?
subj := repl.ReplaceAll(p.Subject, "")
//TODO: Check max msg size
data, err := ioutil.ReadAll(r.Body)
if err != nil {
return err
}
p.logger.Debug("publishing NATS message", zap.String("subject", subj), zap.Bool("with_reply", p.WithReply), zap.Int64("timeout", p.Timeout))
if p.WithReply {
return p.natsRequestReply(subj, data, w)
}
// Otherwise. just publish like normal
err = p.app.conn.Publish(subj, data)
if err != nil {
return err
}
return next.ServeHTTP(w, r)
}
func (p Publish) natsRequestReply(subject string, reqBody []byte, w http.ResponseWriter) error {
m, err := p.app.conn.Request(subject, reqBody, time.Duration(p.Timeout)*time.Millisecond)
// TODO: Make error handlers configurable
if err == nats.ErrNoResponders {
w.WriteHeader(http.StatusNotFound)
return err
} else if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return err
}
_, err = w.Write(m.Data)
return err
}
var (
_ caddyhttp.MiddlewareHandler = (*Publish)(nil)
_ caddy.Provisioner = (*Publish)(nil)
_ caddyfile.Unmarshaler = (*Publish)(nil)
)