Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(client): Add Client.Request helper function
Some refactors in the handler result in cleaner code. The handler now returns extra data for its Error Responses. Improved comments. BREAKING CHANGE: Replace NewInvalidParamsError() with InvalidParams(), un-export constructed Errors that a user does not ever need.
- Loading branch information
Showing
14 changed files
with
357 additions
and
163 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
package jsonrpc2 | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"fmt" | ||
"io/ioutil" | ||
"math/rand" | ||
"net/http" | ||
) | ||
|
||
// Client embeds http.Client and provides a convenient way to make JSON-RPC | ||
// requests. | ||
type Client struct { | ||
http.Client | ||
DebugRequest bool | ||
} | ||
|
||
// Request uses c to make a JSON-RPC 2.0 Request to url with the given method | ||
// and params, and then parses the Response using the provided result for | ||
// Response.Result. Thus, result must be a pointer in order for json.Unmarshal | ||
// to populate it. If Request returns nil, then the request and RPC method call | ||
// were successful and result will be populated, if applicable. If the request | ||
// is successful but the RPC method returns an Error Response, then Request | ||
// will return the Error, which can be checked for by attempting a type | ||
// assertion on the returned error. | ||
// | ||
// Request uses a pseudorandom uint32 for the Request.ID. | ||
// | ||
// If c.DebugRequest is true then the Request and Response will be printed to | ||
// stdout. | ||
func (c *Client) Request(url, method string, params, result interface{}) error { | ||
// Generate a random ID for this request. | ||
reqID := rand.Uint32()%200 + 500 | ||
|
||
// Marshal the JSON RPC Request. | ||
reqJrpc := NewRequest(method, reqID, params) | ||
if c.DebugRequest { | ||
fmt.Println(reqJrpc) | ||
} | ||
reqBytes, err := reqJrpc.MarshalJSON() | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// Make the HTTP request. | ||
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(reqBytes)) | ||
if err != nil { | ||
return err | ||
} | ||
req.Header.Add("Content-Type", "application/json") | ||
res, err := c.Do(req) | ||
if err != nil { | ||
return err | ||
} | ||
defer res.Body.Close() | ||
if res.StatusCode != http.StatusOK && res.StatusCode != http.StatusBadRequest { | ||
return fmt.Errorf("http: %v", res.Status) | ||
} | ||
|
||
// Read the HTTP response. | ||
resBytes, err := ioutil.ReadAll(res.Body) | ||
if err != nil { | ||
return fmt.Errorf("ioutil.ReadAll(http.Response.Body): %v", err) | ||
} | ||
|
||
// Unmarshal the HTTP response into a JSON RPC response. | ||
var resID uint32 | ||
resJrpc := Response{Result: result, ID: &resID} | ||
if err := json.Unmarshal(resBytes, &resJrpc); err != nil { | ||
return fmt.Errorf("json.Unmarshal(%v): %v", string(resBytes), err) | ||
} | ||
if c.DebugRequest { | ||
fmt.Println(resJrpc) | ||
fmt.Println("") | ||
} | ||
if resJrpc.Error != nil { | ||
return *resJrpc.Error | ||
} | ||
if resID != reqID { | ||
return fmt.Errorf("request/response ID mismatch") | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,52 @@ | ||
// Copyright 2018 Adam S Levy. All rights reserved. | ||
// Use of this source code is governed by the MIT license that can be found in | ||
// the LICENSE file. | ||
|
||
package jsonrpc2 | ||
|
||
// ErrorCode represent the int JSON RPC 2.0 error code. | ||
type ErrorCode int | ||
|
||
// Official JSON-RPC 2.0 Spec Error Codes and Messages | ||
const ( | ||
LowestReservedErrorCode ErrorCode = -32768 | ||
ParseErrorCode ErrorCode = -32700 | ||
InvalidRequestCode ErrorCode = -32600 | ||
MethodNotFoundCode ErrorCode = -32601 | ||
InvalidParamsCode ErrorCode = -32602 | ||
InternalErrorCode ErrorCode = -32603 | ||
HighestReservedErrorCode ErrorCode = -32000 | ||
|
||
ParseErrorMessage = "Parse error" | ||
InvalidRequestMessage = "Invalid Request" | ||
MethodNotFoundMessage = "Method not found" | ||
InvalidParamsMessage = "Invalid params" | ||
InternalErrorMessage = "Internal error" | ||
// MinReservedErrorCode is the minimum reserved error code. Method | ||
// defined errors may be less than this value. | ||
MinReservedErrorCode ErrorCode = -32768 | ||
|
||
// ParseErrorCode is returned to the client when invalid JSON was | ||
// received by the server. An error occurred on the server while | ||
// parsing the JSON text. | ||
ParseErrorCode ErrorCode = -32700 | ||
ParseErrorMessage = "Parse error" | ||
|
||
// InvalidRequestCode is returned to the client when the JSON sent is | ||
// not a valid Request object. | ||
InvalidRequestCode ErrorCode = -32600 | ||
InvalidRequestMessage = "Invalid Request" | ||
|
||
// MethodNotFoundCode is returned to the client when the method does | ||
// not exist / is not available. | ||
MethodNotFoundCode ErrorCode = -32601 | ||
MethodNotFoundMessage = "Method not found" | ||
|
||
// InvalidParamsCode is returned to the client if a method is called | ||
// with invalid method parameter(s). MethodFuncs are responsible for | ||
// detecting and returning this error. | ||
InvalidParamsCode ErrorCode = -32602 | ||
InvalidParamsMessage = "Invalid params" | ||
|
||
// InternalErrorCode is returned to the client if an internal error | ||
// occurs such as a MethodFunc panic. | ||
InternalErrorCode ErrorCode = -32603 | ||
InternalErrorMessage = "Internal error" | ||
|
||
// MaxReservedErrorCode is the maximum reserved error code. Method | ||
// defined errors may be greater than this value. | ||
MaxReservedErrorCode ErrorCode = -32000 | ||
) | ||
|
||
// IsReserved returns true if c is within the reserved error code range: | ||
// [LowestReservedErrorCode, HighestReservedErrorCode]. | ||
func (c ErrorCode) IsReserved() bool { | ||
return LowestReservedErrorCode <= c && c <= HighestReservedErrorCode | ||
return MinReservedErrorCode <= c && c <= MaxReservedErrorCode | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,7 +1,5 @@ | ||
module github.com/AdamSLevy/jsonrpc2/v10 | ||
module github.com/AdamSLevy/jsonrpc2/v11 | ||
|
||
require ( | ||
github.com/davecgh/go-spew v1.1.1 // indirect | ||
github.com/pmezard/go-difflib v1.0.0 // indirect | ||
github.com/stretchr/testify v1.2.2 | ||
) | ||
go 1.12 | ||
|
||
require github.com/stretchr/testify v1.3.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,7 @@ | ||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= | ||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= | ||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= | ||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= | ||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= | ||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w= | ||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= | ||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= | ||
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= | ||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= |
Oops, something went wrong.