@@ -6,7 +6,6 @@ package jsonrpc2
6
6
7
7
import (
8
8
"context"
9
- "fmt"
10
9
"sync"
11
10
)
12
11
@@ -53,30 +52,32 @@ type Conn struct {
53
52
54
53
var _ Interface = (* Conn )(nil )
55
54
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
+
56
69
// NewConn creates a new connection object that reads and writes messages from
57
70
// 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 {
59
72
conn := & Conn {
60
73
stream : s ,
61
74
done : make (chan struct {}),
62
75
pending : make (map [ID ]chan * Response ),
63
76
}
64
77
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 )
79
79
}
80
+
80
81
if conn .handle == nil {
81
82
// the default handler reports a method error
82
83
conn .handle = func (ctx context.Context , c * Conn , r * Request ) {
@@ -89,10 +90,12 @@ func NewConn(ctx context.Context, s Stream, options ...interface{}) *Conn {
89
90
// the default canceller does nothing
90
91
conn .cancel = func (context.Context , * Conn , * Request ) {}
91
92
}
93
+
92
94
go func () {
93
95
conn .err = conn .run (ctx )
94
96
close (conn .done )
95
97
}()
98
+
96
99
return conn
97
100
}
98
101
0 commit comments