Skip to content

Commit 4123466

Browse files
committed
jsonrpc2: add functional options
1 parent 4941a11 commit 4123466

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

jsonrpc2.go

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ package jsonrpc2
66

77
import (
88
"context"
9-
"fmt"
109
"sync"
1110
)
1211

@@ -53,30 +52,32 @@ type Conn struct {
5352

5453
var _ Interface = (*Conn)(nil)
5554

55+
type Options func(*Conn)
56+
57+
func WithHandler(h Handler) Options {
58+
return func(c *Conn) {
59+
c.handle = h
60+
}
61+
}
62+
63+
func WithCanceler(cancel Canceler) Options {
64+
return func(c *Conn) {
65+
c.cancel = cancel
66+
}
67+
}
68+
5669
// NewConn creates a new connection object that reads and writes messages from
5770
// the supplied stream and dispatches incoming messages to the supplied handler.
58-
func NewConn(ctx context.Context, s Stream, options ...interface{}) *Conn {
71+
func NewConn(ctx context.Context, s Stream, options ...Options) *Conn {
5972
conn := &Conn{
6073
stream: s,
6174
done: make(chan struct{}),
6275
pending: make(map[ID]chan *Response),
6376
}
6477
for _, opt := range options {
65-
switch opt := opt.(type) {
66-
case Handler:
67-
if conn.handle != nil {
68-
panic("Duplicate Handler function in options list")
69-
}
70-
conn.handle = opt
71-
case Canceler:
72-
if conn.cancel != nil {
73-
panic("Duplicate Canceler function in options list")
74-
}
75-
conn.cancel = opt
76-
default:
77-
panic(fmt.Errorf("Unknown option type %T in options list", opt))
78-
}
78+
opt(conn)
7979
}
80+
8081
if conn.handle == nil {
8182
// the default handler reports a method error
8283
conn.handle = func(ctx context.Context, c *Conn, r *Request) {
@@ -89,10 +90,12 @@ func NewConn(ctx context.Context, s Stream, options ...interface{}) *Conn {
8990
// the default canceller does nothing
9091
conn.cancel = func(context.Context, *Conn, *Request) {}
9192
}
93+
9294
go func() {
9395
conn.err = conn.run(ctx)
9496
close(conn.done)
9597
}()
98+
9699
return conn
97100
}
98101

0 commit comments

Comments
 (0)