@@ -12,6 +12,38 @@ import (
1212 "github.com/nats-io/nats.go"
1313)
1414
15+ // Client is a thin wrapper around *nats.Conn, which is able to serve and invoke wRPC functions
16+ type Client struct {
17+ conn * nats.Conn
18+ prefix string
19+ group string
20+ }
21+
22+ // ClientOpt is option client configuration option passed to NewClient
23+ type ClientOpt func (* Client )
24+
25+ // WithPrefix sets a prefix for this Client
26+ func WithPrefix (prefix string ) ClientOpt {
27+ return func (c * Client ) {
28+ c .prefix = prefix
29+ }
30+ }
31+
32+ // WithGroup sets a queue group for this Client
33+ func WithGroup (group string ) ClientOpt {
34+ return func (c * Client ) {
35+ c .group = group
36+ }
37+ }
38+
39+ func NewClient (conn * nats.Conn , opts ... ClientOpt ) * Client {
40+ c := & Client {conn : conn }
41+ for _ , opt := range opts {
42+ opt (c )
43+ }
44+ return c
45+ }
46+
1547type headerKey struct {}
1648
1749func HeaderFromContext (ctx context.Context ) (nats.Header , bool ) {
@@ -78,20 +110,6 @@ func subscribe(conn *nats.Conn, prefix string, f func(context.Context, []byte),
78110 })
79111}
80112
81- type Client struct {
82- conn * nats.Conn
83- prefix string
84- queueGroup string
85- }
86-
87- func NewClient (conn * nats.Conn , prefix string ) * Client {
88- return & Client {conn : conn , prefix : prefix , queueGroup : "" }
89- }
90-
91- func NewClientWithQueueGroup (conn * nats.Conn , prefix string , queueGroup string ) * Client {
92- return & Client {conn , prefix , queueGroup }
93- }
94-
95113type paramWriter struct {
96114 nc * nats.Conn
97115 init func () (* initState , error )
@@ -447,13 +465,13 @@ func (c *Client) handleMessage(instance string, name string, f func(context.Cont
447465}
448466
449467func (c * Client ) Serve (instance string , name string , f func (context.Context , wrpc.IndexWriteCloser , wrpc.IndexReadCloser ), paths ... wrpc.SubscribePath ) (stop func () error , err error ) {
450- slog .Debug ("serving" , "instance" , instance , "name" , name , "group" , c .queueGroup )
468+ slog .Debug ("serving" , "instance" , instance , "name" , name , "group" , c .group )
451469
452470 subject := invocationSubject (c .prefix , instance , name )
453471 handle := c .handleMessage (instance , name , f , paths ... )
454472 var sub * nats.Subscription
455- if c .queueGroup != "" {
456- sub , err = c .conn .QueueSubscribe (subject , c .queueGroup , handle )
473+ if c .group != "" {
474+ sub , err = c .conn .QueueSubscribe (subject , c .group , handle )
457475 } else {
458476 sub , err = c .conn .Subscribe (subject , handle )
459477 }
0 commit comments