mirror of
https://github.com/sourcegraph/jsonrpc2.git
synced 2026-07-04 16:23:41 +02:00
Make the RequestField.Value an interface{}
This change trades an extra JSON unmarshal in `Request.UnmarshalJSON` for several little casts, checks, and marshals.
This commit is contained in:
parent
f987817f79
commit
83d34e6888
3 changed files with 50 additions and 34 deletions
|
|
@ -2,7 +2,6 @@ package jsonrpc2_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
|
@ -108,18 +107,22 @@ func TestExtraField(t *testing.T) {
|
||||||
t.Error(err)
|
t.Error(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
var sessionId *json.RawMessage
|
var sessionID string
|
||||||
for _, field := range req.ExtraFields {
|
for _, field := range req.ExtraFields {
|
||||||
if field.Name != "sessionId" {
|
if field.Name != "sessionId" {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
sessionId = field.Value
|
var ok bool
|
||||||
|
sessionID, ok = field.Value.(string)
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("\"sessionId\" is not a string: %v", field.Value)
|
||||||
}
|
}
|
||||||
if sessionId == nil {
|
}
|
||||||
|
if sessionID == "" {
|
||||||
replyWithError("sessionId must be set")
|
replyWithError("sessionId must be set")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if string(*sessionId) != `"session"` {
|
if sessionID != "session" {
|
||||||
replyWithError("sessionId has the wrong value")
|
replyWithError("sessionId has the wrong value")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
|
||||||
68
jsonrpc2.go
68
jsonrpc2.go
|
|
@ -33,7 +33,7 @@ type JSONRPC2 interface {
|
||||||
// RequestField is a top-level field that can be added to the JSON-RPC request.
|
// RequestField is a top-level field that can be added to the JSON-RPC request.
|
||||||
type RequestField struct {
|
type RequestField struct {
|
||||||
Name string
|
Name string
|
||||||
Value *json.RawMessage
|
Value interface{}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Request represents a JSON-RPC request or
|
// Request represents a JSON-RPC request or
|
||||||
|
|
@ -83,46 +83,64 @@ func (r Request) MarshalJSON() ([]byte, error) {
|
||||||
|
|
||||||
// UnmarshalJSON implements json.Unmarshaler.
|
// UnmarshalJSON implements json.Unmarshaler.
|
||||||
func (r *Request) UnmarshalJSON(data []byte) error {
|
func (r *Request) UnmarshalJSON(data []byte) error {
|
||||||
var r2 struct {
|
r2 := make(map[string]interface{})
|
||||||
Method string `json:"method"`
|
|
||||||
Params *json.RawMessage `json:"params,omitempty"`
|
|
||||||
Meta *json.RawMessage `json:"meta,omitempty"`
|
|
||||||
ID *ID `json:"id"`
|
|
||||||
}
|
|
||||||
// This is used to get the extra fields, which are not type-safe.
|
|
||||||
r3 := make(map[string]*json.RawMessage)
|
|
||||||
|
|
||||||
// Detect if the "params" field is JSON "null" or just not present
|
// Detect if the "params" field is JSON "null" or just not present
|
||||||
// by seeing if the field gets overwritten to nil.
|
// by seeing if the field gets overwritten to nil.
|
||||||
r2.Params = &json.RawMessage{}
|
emptyParams := &json.RawMessage{}
|
||||||
|
r2["params"] = emptyParams
|
||||||
|
|
||||||
if err := json.Unmarshal(data, &r2); err != nil {
|
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||||
|
decoder.UseNumber()
|
||||||
|
if err := decoder.Decode(&r2); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if err := json.Unmarshal(data, &r3); err != nil {
|
var ok bool
|
||||||
return err
|
r.Method, ok = r2["method"].(string)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("missing method field")
|
||||||
}
|
}
|
||||||
r.Method = r2.Method
|
|
||||||
switch {
|
switch {
|
||||||
case r2.Params == nil:
|
case r2["params"] == nil:
|
||||||
r.Params = &jsonNull
|
r.Params = &jsonNull
|
||||||
case len(*r2.Params) == 0:
|
case r2["params"] == emptyParams:
|
||||||
r.Params = nil
|
r.Params = nil
|
||||||
default:
|
default:
|
||||||
r.Params = r2.Params
|
b, err := json.Marshal(r2["params"])
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal params: %w", err)
|
||||||
}
|
}
|
||||||
r.Meta = r2.Meta
|
r.Params = (*json.RawMessage)(&b)
|
||||||
if r2.ID == nil {
|
}
|
||||||
|
meta, ok := r2["meta"]
|
||||||
|
if ok {
|
||||||
|
b, err := json.Marshal(meta)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to marshal Meta: %w", err)
|
||||||
|
}
|
||||||
|
r.Meta = (*json.RawMessage)(&b)
|
||||||
|
}
|
||||||
|
switch rawID := r2["id"].(type) {
|
||||||
|
case nil:
|
||||||
r.ID = ID{}
|
r.ID = ID{}
|
||||||
r.Notif = true
|
r.Notif = true
|
||||||
} else {
|
case string:
|
||||||
r.ID = *r2.ID
|
r.ID = ID{Str: rawID, IsString: true}
|
||||||
r.Notif = false
|
r.Notif = false
|
||||||
|
case json.Number:
|
||||||
|
id, err := rawID.Int64()
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("failed to unmarshal ID: %w", err)
|
||||||
|
}
|
||||||
|
r.ID = ID{Num: uint64(id)}
|
||||||
|
r.Notif = false
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unexpected ID type: %T", rawID)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear the extra fields before populating them again.
|
// Clear the extra fields before populating them again.
|
||||||
r.ExtraFields = nil
|
r.ExtraFields = nil
|
||||||
for name, value := range r3 {
|
for name, value := range r2 {
|
||||||
switch name {
|
switch name {
|
||||||
case "id", "jsonrpc", "meta", "method", "params":
|
case "id", "jsonrpc", "meta", "method", "params":
|
||||||
continue
|
continue
|
||||||
|
|
@ -161,13 +179,9 @@ func (r *Request) SetMeta(v interface{}) error {
|
||||||
// JSON representation of the request, as a way to add arbitrary extensions to
|
// JSON representation of the request, as a way to add arbitrary extensions to
|
||||||
// JSON RPC 2.0. If JSON marshaling fails, it returns an error.
|
// JSON RPC 2.0. If JSON marshaling fails, it returns an error.
|
||||||
func (r *Request) SetExtraField(name string, v interface{}) error {
|
func (r *Request) SetExtraField(name string, v interface{}) error {
|
||||||
b, err := json.Marshal(v)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
r.ExtraFields = append(r.ExtraFields, RequestField{
|
r.ExtraFields = append(r.ExtraFields, RequestField{
|
||||||
Name: name,
|
Name: name,
|
||||||
Value: (*json.RawMessage)(&b),
|
Value: v,
|
||||||
})
|
})
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,6 @@ func TestAnyMessage(t *testing.T) {
|
||||||
func TestRequest_MarshalUnmarshalJSON(t *testing.T) {
|
func TestRequest_MarshalUnmarshalJSON(t *testing.T) {
|
||||||
null := json.RawMessage("null")
|
null := json.RawMessage("null")
|
||||||
obj := json.RawMessage(`{"foo":"bar"}`)
|
obj := json.RawMessage(`{"foo":"bar"}`)
|
||||||
requestFieldValue := json.RawMessage(`"session"`)
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
data []byte
|
data []byte
|
||||||
want Request
|
want Request
|
||||||
|
|
@ -58,7 +57,7 @@ func TestRequest_MarshalUnmarshalJSON(t *testing.T) {
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
data: []byte(`{"id":123,"jsonrpc":"2.0","method":"m","sessionId":"session"}`),
|
data: []byte(`{"id":123,"jsonrpc":"2.0","method":"m","sessionId":"session"}`),
|
||||||
want: Request{ID: ID{Num: 123}, Method: "m", Params: nil, ExtraFields: []RequestField{{Name: "sessionId", Value: &requestFieldValue}}},
|
want: Request{ID: ID{Num: 123}, Method: "m", Params: nil, ExtraFields: []RequestField{{Name: "sessionId", Value: "session"}}},
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
for _, test := range tests {
|
for _, test := range tests {
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue