Skip to content

Commit

Permalink
jsonrpc add id from request to response (#742)
Browse files Browse the repository at this point in the history
* jsonrpc add id from request to response

* add test for marshal id

* organize null test
  • Loading branch information
wangzuo authored and peterbourgon committed Aug 7, 2018
1 parent de60aef commit 631bc1e
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
11 changes: 11 additions & 0 deletions transport/http/jsonrpc/request_response_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ func (id *RequestID) UnmarshalJSON(b []byte) error {
return nil
}

func (id *RequestID) MarshalJSON() ([]byte, error) {
if id.intError == nil {
return json.Marshal(id.intValue)
} else if id.floatError == nil {
return json.Marshal(id.floatValue)
} else {
return json.Marshal(id.stringValue)
}
}

// Int returns the ID as an integer value.
// An error is returned if the ID can't be treated as an int.
func (id *RequestID) Int() (int, error) {
Expand All @@ -59,6 +69,7 @@ type Response struct {
JSONRPC string `json:"jsonrpc"`
Result json.RawMessage `json:"result,omitempty"`
Error *Error `json:"error,omitempty"`
ID *RequestID `json:"id"`
}

const (
Expand Down
27 changes: 27 additions & 0 deletions transport/http/jsonrpc/request_response_types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,30 @@ func TestCanUnmarshalNullID(t *testing.T) {
t.Fatalf("Expected ID to be nil, got %+v.\n", r.ID)
}
}

func TestCanMarshalID(t *testing.T) {
cases := []struct {
JSON string
expType string
expValue interface{}
}{
{`12345`, "int", 12345},
{`12345.6`, "float", 12345.6},
{`"stringaling"`, "string", "stringaling"},
{`null`, "null", nil},
}

for _, c := range cases {
req := jsonrpc.Request{}
JSON := fmt.Sprintf(`{"jsonrpc":"2.0","id":%s}`, c.JSON)
json.Unmarshal([]byte(JSON), &req)
resp := jsonrpc.Response{ID: req.ID, JSONRPC: req.JSONRPC}

want := JSON
bol, _ := json.Marshal(resp)
got := string(bol)
if got != want {
t.Fatalf("'%s': want %s, got %s.", c.expType, want, got)
}
}
}
1 change: 1 addition & 0 deletions transport/http/jsonrpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,7 @@ func (s Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

res := Response{
ID: req.ID,
JSONRPC: Version,
}

Expand Down

0 comments on commit 631bc1e

Please sign in to comment.