From f03b4ba540f492516ed7a510e3b46845cf7e6f11 Mon Sep 17 00:00:00 2001 From: Kiel barry Date: Mon, 9 Jul 2018 14:58:53 -0700 Subject: [PATCH] rpc: various golint warning fixes --- rpc/client.go | 11 ++++++++++- rpc/http.go | 15 ++++++++++++--- rpc/json.go | 36 ++++++++++++++++++------------------ rpc/json_test.go | 4 ++-- rpc/server.go | 4 ++-- rpc/subscription.go | 4 ++-- rpc/subscription_test.go | 6 +++--- rpc/types.go | 1 + rpc/utils.go | 10 +++++----- 9 files changed, 55 insertions(+), 36 deletions(-) diff --git a/rpc/client.go b/rpc/client.go index a2ef2ed6b6..a50b5e4c18 100644 --- a/rpc/client.go +++ b/rpc/client.go @@ -36,6 +36,7 @@ import ( "github.com/ethereum/go-ethereum/log" ) +// Vars hardcodes custom error messages. var ( ErrClientQuit = errors.New("client is closed") ErrNoResult = errors.New("no result in JSON-RPC response") @@ -191,29 +192,37 @@ func (io StdIOConn) Write(b []byte) (n int, err error) { return os.Stdout.Write(b) } +// Close is a noop. func (io StdIOConn) Close() error { return nil } +// LocalAddr sets the address of a Unix domain socket end point. func (io StdIOConn) LocalAddr() net.Addr { return &net.UnixAddr{Name: "stdio", Net: "stdio"} } +// RemoteAddr sets the remote address of a Unix domain socket end point. func (io StdIOConn) RemoteAddr() net.Addr { return &net.UnixAddr{Name: "stdio", Net: "stdio"} } +// SetDeadline sets the operation, network type, and address of an error. func (io StdIOConn) SetDeadline(t time.Time) error { return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} } +// SetReadDeadline sets the operation, network type, and address of an error. func (io StdIOConn) SetReadDeadline(t time.Time) error { return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} } +// SetWriteDeadline sets the operation, network type, and address of an error. func (io StdIOConn) SetWriteDeadline(t time.Time) error { return &net.OpError{Op: "set", Net: "stdio", Source: nil, Addr: nil, Err: errors.New("deadline not supported")} } + +// DialStdIO returns a new client instance with ctx values. func DialStdIO(ctx context.Context) (*Client, error) { return newClient(ctx, func(_ context.Context) (net.Conn, error) { return StdIOConn{}, nil @@ -329,7 +338,7 @@ func (c *Client) BatchCall(b []BatchElem) error { return c.BatchCallContext(ctx, b) } -// BatchCall sends all given requests as a single batch and waits for the server +// BatchCallContext sends all given requests as a single batch and waits for the server // to return a response for all of them. The wait duration is bounded by the // context's deadline. // diff --git a/rpc/http.go b/rpc/http.go index 6388d68961..04f2c67c4c 100644 --- a/rpc/http.go +++ b/rpc/http.go @@ -173,6 +173,12 @@ func NewHTTPServer(cors []string, vhosts []string, srv *Server) *http.Server { } } +type contextKey string + +func contextString(c contextKey) string { + return string(c) +} + // ServeHTTP serves JSON-RPC requests over HTTP. func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Permit dumb empty requests for remote health-checks (AWS) @@ -183,13 +189,16 @@ func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { http.Error(w, err.Error(), code) return } + + rem, sch, loc := contextKey("remote"), contextKey("scheme"), contextKey("local") + // All checks passed, create a codec that reads direct from the request body // untilEOF and writes the response to w and order the server to process a // single request. ctx := r.Context() - ctx = context.WithValue(ctx, "remote", r.RemoteAddr) - ctx = context.WithValue(ctx, "scheme", r.Proto) - ctx = context.WithValue(ctx, "local", r.Host) + ctx = context.WithValue(ctx, rem, r.RemoteAddr) + ctx = context.WithValue(ctx, sch, r.Proto) + ctx = context.WithValue(ctx, loc, r.Host) body := io.LimitReader(r.Body, maxRequestContentLength) codec := NewJSONCodec(&httpReadWriteNopCloser{body, w}) diff --git a/rpc/json.go b/rpc/json.go index a523eeb8ef..ae235b12ef 100644 --- a/rpc/json.go +++ b/rpc/json.go @@ -40,13 +40,13 @@ const ( type jsonRequest struct { Method string `json:"method"` Version string `json:"jsonrpc"` - Id json.RawMessage `json:"id,omitempty"` + ID json.RawMessage `json:"id,omitempty"` Payload json.RawMessage `json:"params,omitempty"` } type jsonSuccessResponse struct { Version string `json:"jsonrpc"` - Id interface{} `json:"id,omitempty"` + ID interface{} `json:"id,omitempty"` Result interface{} `json:"result"` } @@ -58,7 +58,7 @@ type jsonError struct { type jsonErrResponse struct { Version string `json:"jsonrpc"` - Id interface{} `json:"id,omitempty"` + ID interface{} `json:"id,omitempty"` Error jsonError `json:"error"` } @@ -150,17 +150,17 @@ func (c *jsonCodec) ReadRequestHeaders() ([]rpcRequest, bool, Error) { return parseRequest(incomingMsg) } -// checkReqId returns an error when the given reqId isn't valid for RPC method calls. +// checkReqID returns an error when the given reqID isn't valid for RPC method calls. // valid id's are strings, numbers or null -func checkReqId(reqId json.RawMessage) error { - if len(reqId) == 0 { +func checkReqID(reqID json.RawMessage) error { + if len(reqID) == 0 { return fmt.Errorf("missing request id") } - if _, err := strconv.ParseFloat(string(reqId), 64); err == nil { + if _, err := strconv.ParseFloat(string(reqID), 64); err == nil { return nil } var str string - if err := json.Unmarshal(reqId, &str); err == nil { + if err := json.Unmarshal(reqID, &str); err == nil { return nil } return fmt.Errorf("invalid request id") @@ -175,13 +175,13 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { return nil, false, &invalidMessageError{err.Error()} } - if err := checkReqId(in.Id); err != nil { + if err := checkReqID(in.ID); err != nil { return nil, false, &invalidMessageError{err.Error()} } // subscribe are special, they will always use `subscribeMethod` as first param in the payload if strings.HasSuffix(in.Method, subscribeMethodSuffix) { - reqs := []rpcRequest{{id: &in.Id, isPubSub: true}} + reqs := []rpcRequest{{id: &in.ID, isPubSub: true}} if len(in.Payload) > 0 { // first param must be subscription name var subscribeMethod [1]string @@ -198,7 +198,7 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { } if strings.HasSuffix(in.Method, unsubscribeMethodSuffix) { - return []rpcRequest{{id: &in.Id, isPubSub: true, + return []rpcRequest{{id: &in.ID, isPubSub: true, method: in.Method, params: in.Payload}}, false, nil } @@ -209,10 +209,10 @@ func parseRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) { // regular RPC call if len(in.Payload) == 0 { - return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id}}, false, nil + return []rpcRequest{{service: elems[0], method: elems[1], id: &in.ID}}, false, nil } - return []rpcRequest{{service: elems[0], method: elems[1], id: &in.Id, params: in.Payload}}, false, nil + return []rpcRequest{{service: elems[0], method: elems[1], id: &in.ID, params: in.Payload}}, false, nil } // parseBatchRequest will parse a batch request into a collection of requests from the given RawMessage, an indication @@ -225,11 +225,11 @@ func parseBatchRequest(incomingMsg json.RawMessage) ([]rpcRequest, bool, Error) requests := make([]rpcRequest, len(in)) for i, r := range in { - if err := checkReqId(r.Id); err != nil { + if err := checkReqID(r.ID); err != nil { return nil, false, &invalidMessageError{err.Error()} } - id := &in[i].Id + id := &in[i].ID // subscribe are special, they will always use `subscriptionMethod` as first param in the payload if strings.HasSuffix(r.Method, subscribeMethodSuffix) { @@ -320,18 +320,18 @@ func parsePositionalArguments(rawArgs json.RawMessage, types []reflect.Type) ([] // CreateResponse will create a JSON-RPC success response with the given id and reply as result. func (c *jsonCodec) CreateResponse(id interface{}, reply interface{}) interface{} { - return &jsonSuccessResponse{Version: jsonrpcVersion, Id: id, Result: reply} + return &jsonSuccessResponse{Version: jsonrpcVersion, ID: id, Result: reply} } // CreateErrorResponse will create a JSON-RPC error response with the given id and error. func (c *jsonCodec) CreateErrorResponse(id interface{}, err Error) interface{} { - return &jsonErrResponse{Version: jsonrpcVersion, Id: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}} + return &jsonErrResponse{Version: jsonrpcVersion, ID: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error()}} } // CreateErrorResponseWithInfo will create a JSON-RPC error response with the given id and error. // info is optional and contains additional information about the error. When an empty string is passed it is ignored. func (c *jsonCodec) CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{} { - return &jsonErrResponse{Version: jsonrpcVersion, Id: id, + return &jsonErrResponse{Version: jsonrpcVersion, ID: id, Error: jsonError{Code: err.ErrorCode(), Message: err.Error(), Data: info}} } diff --git a/rpc/json_test.go b/rpc/json_test.go index 5048d2f7a0..d121c8297f 100644 --- a/rpc/json_test.go +++ b/rpc/json_test.go @@ -69,8 +69,8 @@ func TestJSONRequestParsing(t *testing.T) { t.Fatalf("Expected method 'Add' but got '%s'", requests[0].method) } - if rawId, ok := requests[0].id.(*json.RawMessage); ok { - id, e := strconv.ParseInt(string(*rawId), 0, 64) + if rawID, ok := requests[0].id.(*json.RawMessage); ok { + id, e := strconv.ParseInt(string(*rawID), 0, 64) if e != nil { t.Fatalf("%v", e) } diff --git a/rpc/server.go b/rpc/server.go index 8925419fe0..131e66166a 100644 --- a/rpc/server.go +++ b/rpc/server.go @@ -29,7 +29,7 @@ import ( "gopkg.in/fatih/set.v0" ) -const MetadataApi = "rpc" +const MetadataAPI = "rpc" // CodecOption specifies which type of messages this codec supports type CodecOption int @@ -53,7 +53,7 @@ func NewServer() *Server { // register a default service which will provide meta information about the RPC service such as the services and // methods it offers. rpcService := &RPCService{server} - server.RegisterName(MetadataApi, rpcService) + server.RegisterName(MetadataAPI, rpcService) return server } diff --git a/rpc/subscription.go b/rpc/subscription.go index 6ce7befa1d..28e1fe7978 100644 --- a/rpc/subscription.go +++ b/rpc/subscription.go @@ -25,14 +25,14 @@ import ( var ( // ErrNotificationsUnsupported is returned when the connection doesn't support notifications ErrNotificationsUnsupported = errors.New("notifications not supported") - // ErrNotificationNotFound is returned when the notification for the given id is not found + // ErrSubscriptionNotFound is returned when the notification for the given id is not found ErrSubscriptionNotFound = errors.New("subscription not found") ) // ID defines a pseudo random number that is used to identify RPC subscriptions. type ID string -// a Subscription is created by a notifier and tight to that notifier. The client can use +// Subscription is created by a notifier and tied to that notifier. The client can use // this subscription to wait for an unsubscribe request for the client, see Err(). type Subscription struct { ID ID diff --git a/rpc/subscription_test.go b/rpc/subscription_test.go index 0ba177e63b..96c80b74ae 100644 --- a/rpc/subscription_test.go +++ b/rpc/subscription_test.go @@ -195,7 +195,7 @@ func waitForMessages(t *testing.T, in *json.Decoder, successes chan<- jsonSucces if _, found := msg["result"]; found { successes <- jsonSuccessResponse{ Version: msg["jsonrpc"].(string), - Id: msg["id"], + ID: msg["id"], Result: msg["result"], } continue @@ -204,7 +204,7 @@ func waitForMessages(t *testing.T, in *json.Decoder, successes chan<- jsonSucces params := msg["params"].(map[string]interface{}) failures <- jsonErrResponse{ Version: msg["jsonrpc"].(string), - Id: msg["id"], + ID: msg["id"], Error: jsonError{int(params["subscription"].(float64)), params["message"].(string), params["data"]}, } continue @@ -304,7 +304,7 @@ func TestSubscriptionMultipleNamespaces(t *testing.T) { case err := <-errors: t.Fatal(err) case suc := <-successes: // subscription created - subids[namespaces[int(suc.Id.(float64))]] = suc.Result.(string) + subids[namespaces[int(suc.ID.(float64))]] = suc.Result.(string) case failure := <-failures: t.Errorf("received error: %v", failure.Error) case notification := <-notifications: diff --git a/rpc/types.go b/rpc/types.go index f2375604ed..312c9fca4e 100644 --- a/rpc/types.go +++ b/rpc/types.go @@ -160,6 +160,7 @@ func (bn *BlockNumber) UnmarshalJSON(data []byte) error { return nil } +// Int64 casts the bn into int64. func (bn BlockNumber) Int64() int64 { return (int64)(bn) } diff --git a/rpc/utils.go b/rpc/utils.go index 7f7ac4520b..1ba364241f 100644 --- a/rpc/utils.go +++ b/rpc/utils.go @@ -215,12 +215,12 @@ func NewID() ID { } } - rpcId := hex.EncodeToString(id) + rpcID := hex.EncodeToString(id) // rpc ID's are RPC quantities, no leading zero's and 0 is 0x0 - rpcId = strings.TrimLeft(rpcId, "0") - if rpcId == "" { - rpcId = "0" + rpcID = strings.TrimLeft(rpcID, "0") + if rpcID == "" { + rpcID = "0" } - return ID("0x" + rpcId) + return ID("0x" + rpcID) }