From 456318691a5caa7b1f41b546e1fcfb3e272cf5aa Mon Sep 17 00:00:00 2001 From: s3rj1k Date: Sat, 2 Nov 2019 22:31:21 +0200 Subject: [PATCH 1/2] fix some golangci-lint, revive linter warnings Signed-off-by: s3rj1k --- handler_with_error.go | 1 + jsonrpc2.go | 44 +++++++++++++++++++++++-------------------- jsonrpc2_test.go | 24 ++++++++++++----------- websocket/stream.go | 10 +++++----- 4 files changed, 43 insertions(+), 36 deletions(-) diff --git a/handler_with_error.go b/handler_with_error.go index 6f056cc..13ac1c0 100644 --- a/handler_with_error.go +++ b/handler_with_error.go @@ -11,6 +11,7 @@ func HandlerWithError(handleFunc func(context.Context, *Conn, *Request) (result return &HandlerWithErrorConfigurer{handleFunc: handleFunc} } +// HandlerWithErrorConfigurer is a handler configuration struct type HandlerWithErrorConfigurer struct { handleFunc func(context.Context, *Conn, *Request) (result interface{}, err error) suppressErrClosed bool diff --git a/jsonrpc2.go b/jsonrpc2.go index 478a768..00f4acf 100644 --- a/jsonrpc2.go +++ b/jsonrpc2.go @@ -84,11 +84,12 @@ func (r *Request) UnmarshalJSON(data []byte) error { return err } r.Method = r2.Method - if r2.Params == nil { + switch { + case r2.Params == nil: r.Params = &jsonNull - } else if len(*r2.Params) == 0 { + case len(*r2.Params) == 0: r.Params = nil - } else { + default: r.Params = r2.Params } r.Meta = r2.Meta @@ -212,22 +213,22 @@ func (e *Error) Error() string { return fmt.Sprintf("jsonrpc2: code %v message: %s", e.Code, e.Message) } +// Errors defined in the JSON-RPC spec. See +// http://www.jsonrpc.org/specification#error_object. const ( - // Errors defined in the JSON-RPC spec. See - // http://www.jsonrpc.org/specification#error_object. - CodeParseError = -32700 - CodeInvalidRequest = -32600 - CodeMethodNotFound = -32601 - CodeInvalidParams = -32602 - CodeInternalError = -32603 - codeServerErrorStart = -32099 - codeServerErrorEnd = -32000 + CodeParseError = -32700 + CodeInvalidRequest = -32600 + CodeMethodNotFound = -32601 + CodeInvalidParams = -32602 + CodeInternalError = -32603 + // codeServerErrorStart = -32099 + // codeServerErrorEnd = -32000 ) // Handler handles JSON-RPC requests and notifications. type Handler interface { // Handle is called to handle a request. No other requests are handled - // until it returns. If you do not require strict ordering behaviour + // until it returns. If you do not require strict ordering behavior // of received RPCs, it is suggested to wrap your handler in // AsyncHandler. Handle(context.Context, *Conn, *Request) @@ -345,7 +346,7 @@ func (c *Conn) Close() error { return c.stream.Close() } -func (c *Conn) send(ctx context.Context, m *anyMessage, wait bool) (cc *call, err error) { +func (c *Conn) send(_ context.Context, m *anyMessage, wait bool) (cc *call, err error) { c.sending.Lock() defer c.sending.Unlock() @@ -441,7 +442,6 @@ func (c *Conn) Call(ctx context.Context, method string, params, result interface if call.response.Result == nil { call.response.Result = &jsonNull } - // TODO(sqs): error handling if err := json.Unmarshal(*call.response.Result, result); err != nil { return err } @@ -642,17 +642,18 @@ func (m *anyMessage) UnmarshalJSON(data []byte) error { if len(msgs) == 0 { return errors.New("jsonrpc2: invalid empty batch") } - for _, msg := range msgs { - if err := checkType(&msg); err != nil { + for i := range msgs { + var m = msgs[i] + if err := checkType(&m); err != nil { return err } } } else { - var msg msg - if err := json.Unmarshal(data, &msg); err != nil { + var m msg + if err := json.Unmarshal(data, &m); err != nil { return err } - if err := checkType(&msg); err != nil { + if err := checkType(&m); err != nil { return err } } @@ -694,7 +695,10 @@ func (v *anyValueWithExplicitNull) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &v.value) } +/* var ( errInvalidRequestJSON = errors.New("jsonrpc2: request must be either a JSON object or JSON array") errInvalidResponseJSON = errors.New("jsonrpc2: response must be either a JSON object or JSON array") ) +*/ + diff --git a/jsonrpc2_test.go b/jsonrpc2_test.go index f6eb430..9710ab5 100644 --- a/jsonrpc2_test.go +++ b/jsonrpc2_test.go @@ -42,11 +42,11 @@ func TestResponse_MarshalJSON_jsonrpc(t *testing.T) { func TestResponseMarshalJSON_Notif(t *testing.T) { tests := map[*jsonrpc2.Request]bool{ - &jsonrpc2.Request{ID: jsonrpc2.ID{Num: 0}}: true, - &jsonrpc2.Request{ID: jsonrpc2.ID{Num: 1}}: true, - &jsonrpc2.Request{ID: jsonrpc2.ID{Str: "", IsString: true}}: true, - &jsonrpc2.Request{ID: jsonrpc2.ID{Str: "a", IsString: true}}: true, - &jsonrpc2.Request{Notif: true}: false, + {ID: jsonrpc2.ID{Num: 0}}: true, + {ID: jsonrpc2.ID{Num: 1}}: true, + {ID: jsonrpc2.ID{Str: "", IsString: true}}: true, + {ID: jsonrpc2.ID{Str: "a", IsString: true}}: true, + {Notif: true}: false, } for r, wantIDKey := range tests { b, err := json.Marshal(r) @@ -125,7 +125,7 @@ func TestClientServer(t *testing.T) { if lis == nil { return // already closed } - if err := lis.Close(); err != nil { + if err = lis.Close(); err != nil { if !strings.HasSuffix(err.Error(), "use of closed network connection") { t.Fatal(err) } @@ -134,7 +134,7 @@ func TestClientServer(t *testing.T) { ha := testHandlerA{t: t} go func() { - if err := serve(ctx, lis, &ha); err != nil { + if err = serve(ctx, lis, &ha); err != nil { if !strings.HasSuffix(err.Error(), "use of closed network connection") { t.Error(err) } @@ -169,10 +169,11 @@ func TestClientServer(t *testing.T) { })) defer s.Close() - c, _, err := websocket.DefaultDialer.Dial(strings.Replace(s.URL, "http:", "ws:", 1), nil) + c, resp, err := websocket.DefaultDialer.Dial(strings.Replace(s.URL, "http:", "ws:", 1), nil) if err != nil { t.Fatal(err) } + defer resp.Body.Close() defer c.Close() testClientServer(ctx, t, websocketjsonrpc2.NewObjectStream(c)) @@ -296,9 +297,10 @@ func TestHandlerBlocking(t *testing.T) { a, b := inMemoryPeerConns() defer a.Close() defer b.Close() - - var wg sync.WaitGroup - var params []int + var ( + wg sync.WaitGroup + params []int + ) handler := handlerFunc(func(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) { var i int _ = json.Unmarshal(*req.Params, &i) diff --git a/websocket/stream.go b/websocket/stream.go index 26313a0..193363c 100644 --- a/websocket/stream.go +++ b/websocket/stream.go @@ -5,18 +5,18 @@ package websocket import ( "io" - "github.com/gorilla/websocket" + ws "github.com/gorilla/websocket" ) // A ObjectStream is a jsonrpc2.ObjectStream that uses a WebSocket to // send and receive JSON-RPC 2.0 objects. type ObjectStream struct { - conn *websocket.Conn + conn *ws.Conn } // NewObjectStream creates a new jsonrpc2.ObjectStream for sending and // receiving JSON-RPC 2.0 objects over a WebSocket. -func NewObjectStream(conn *websocket.Conn) ObjectStream { +func NewObjectStream(conn *ws.Conn) ObjectStream { return ObjectStream{conn: conn} } @@ -28,8 +28,8 @@ func (t ObjectStream) WriteObject(obj interface{}) error { // ReadObject implements jsonrpc2.ObjectStream. func (t ObjectStream) ReadObject(v interface{}) error { err := t.conn.ReadJSON(v) - if e, ok := err.(*websocket.CloseError); ok { - if e.Code == websocket.CloseAbnormalClosure && e.Text == io.ErrUnexpectedEOF.Error() { + if e, ok := err.(*ws.CloseError); ok { + if e.Code == ws.CloseAbnormalClosure && e.Text == io.ErrUnexpectedEOF.Error() { // Suppress a noisy (but harmless) log message by // unwrapping this error. err = io.ErrUnexpectedEOF From 375ca94e9cc0def97082721721dcd192fdf5d35d Mon Sep 17 00:00:00 2001 From: Quinn Slack Date: Sat, 2 Nov 2019 21:39:58 -0700 Subject: [PATCH 2/2] add go module, simplify some cleanups --- go.mod | 5 +++++ go.sum | 2 ++ handler_with_error.go | 3 ++- jsonrpc2.go | 14 ++------------ 4 files changed, 11 insertions(+), 13 deletions(-) create mode 100644 go.mod create mode 100644 go.sum diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..cd46ca6 --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module github.com/sourcegraph/jsonrpc2 + +go 1.13 + +require github.com/gorilla/websocket v1.4.1 diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1f9b923 --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= diff --git a/handler_with_error.go b/handler_with_error.go index 13ac1c0..51d087b 100644 --- a/handler_with_error.go +++ b/handler_with_error.go @@ -11,7 +11,8 @@ func HandlerWithError(handleFunc func(context.Context, *Conn, *Request) (result return &HandlerWithErrorConfigurer{handleFunc: handleFunc} } -// HandlerWithErrorConfigurer is a handler configuration struct + +// HandlerWithErrorConfigurer is a handler created by HandlerWithError. type HandlerWithErrorConfigurer struct { handleFunc func(context.Context, *Conn, *Request) (result interface{}, err error) suppressErrClosed bool diff --git a/jsonrpc2.go b/jsonrpc2.go index 00f4acf..594f754 100644 --- a/jsonrpc2.go +++ b/jsonrpc2.go @@ -221,8 +221,6 @@ const ( CodeMethodNotFound = -32601 CodeInvalidParams = -32602 CodeInternalError = -32603 - // codeServerErrorStart = -32099 - // codeServerErrorEnd = -32000 ) // Handler handles JSON-RPC requests and notifications. @@ -642,9 +640,8 @@ func (m *anyMessage) UnmarshalJSON(data []byte) error { if len(msgs) == 0 { return errors.New("jsonrpc2: invalid empty batch") } - for i := range msgs { - var m = msgs[i] - if err := checkType(&m); err != nil { + for _, msg := range msgs { + if err := checkType(&msg); err != nil { return err } } @@ -695,10 +692,3 @@ func (v *anyValueWithExplicitNull) UnmarshalJSON(data []byte) error { return json.Unmarshal(data, &v.value) } -/* -var ( - errInvalidRequestJSON = errors.New("jsonrpc2: request must be either a JSON object or JSON array") - errInvalidResponseJSON = errors.New("jsonrpc2: response must be either a JSON object or JSON array") -) -*/ -