@@ -18,6 +18,7 @@ type Subscriber struct {
18
18
before []RequestFunc
19
19
after []SubscriberResponseFunc
20
20
errorEncoder ErrorEncoder
21
+ finalizer []SubscriberFinalizerFunc
21
22
logger log.Logger
22
23
}
23
24
@@ -73,12 +74,26 @@ func SubscriberErrorLogger(logger log.Logger) SubscriberOption {
73
74
return func (s * Subscriber ) { s .logger = logger }
74
75
}
75
76
77
+ // SubscriberFinalizer is executed at the end of every request from a publisher through NATS.
78
+ // By default, no finalizer is registered.
79
+ func SubscriberFinalizer (f ... SubscriberFinalizerFunc ) SubscriberOption {
80
+ return func (s * Subscriber ) { s .finalizer = f }
81
+ }
82
+
76
83
// ServeMsg provides nats.MsgHandler.
77
84
func (s Subscriber ) ServeMsg (nc * nats.Conn ) func (msg * nats.Msg ) {
78
85
return func (msg * nats.Msg ) {
79
86
ctx , cancel := context .WithCancel (context .Background ())
80
87
defer cancel ()
81
88
89
+ if len (s .finalizer ) > 0 {
90
+ defer func () {
91
+ for _ , f := range s .finalizer {
92
+ f (ctx , msg )
93
+ }
94
+ }()
95
+ }
96
+
82
97
for _ , f := range s .before {
83
98
ctx = f (ctx , msg )
84
99
}
@@ -125,6 +140,11 @@ func (s Subscriber) ServeMsg(nc *nats.Conn) func(msg *nats.Msg) {
125
140
// types.
126
141
type ErrorEncoder func (ctx context.Context , err error , reply string , nc * nats.Conn )
127
142
143
+ // ServerFinalizerFunc can be used to perform work at the end of an request
144
+ // from a publisher, after the response has been written to the publisher. The principal
145
+ // intended use is for request logging.
146
+ type SubscriberFinalizerFunc func (ctx context.Context , msg * nats.Msg )
147
+
128
148
// NopRequestDecoder is a DecodeRequestFunc that can be used for requests that do not
129
149
// need to be decoded, and simply returns nil, nil.
130
150
func NopRequestDecoder (_ context.Context , _ * nats.Msg ) (interface {}, error ) {
0 commit comments