@@ -5,8 +5,9 @@ package jsonrpc2
55import (
66 "context"
77 "encoding/json"
8- "math/rand"
98 "net/http"
9+
10+ uuid "github.com/gofrs/uuid"
1011)
1112
1213const (
@@ -33,10 +34,10 @@ func (e *ResponseError) Error() string {
3334// Request represents a jsonrpc2 request.
3435//easyjson:json
3536type Request struct {
36- Version string `json:"jsonrpc"`
37- Method string `json:"method"`
38- Params interface {} `json:"params"`
39- Id uint64 `json:"id"`
37+ Version string `json:"jsonrpc"`
38+ Method string `json:"method"`
39+ Params interface {} `json:"params"`
40+ Id * json. RawMessage `json:"id"`
4041}
4142
4243// Request represents a jsonrpc2 response.
@@ -45,6 +46,7 @@ type Response struct {
4546 Version string `json:"jsonrpc"`
4647 Result * json.RawMessage `json:"result"`
4748 Error * json.RawMessage `json:"error"`
49+ Id * json.RawMessage `json:"id"`
4850}
4951
5052type (
@@ -85,7 +87,20 @@ func NewClient(rpcEndpointURL string, options ...clientOption) Client {
8587
8688// Call makes and does jsonrpc2 request.
8789func (c * client ) Call (ctx context.Context , methodName string , params interface {}, result interface {}) error {
88- encodedReq , err := encodeRequest (methodName , params )
90+ requestID , _ := RequestIDFromContext (ctx )
91+
92+ if requestID == nil {
93+ reqUUID , err := uuid .NewV4 ()
94+ if err != nil {
95+ return err
96+ }
97+
98+ // We do not use json.Marshal because we know the json representation of a string.
99+ requestIDVal := json .RawMessage ("\" " + reqUUID .String () + "\" " )
100+ requestID = & requestIDVal
101+ }
102+
103+ encodedReq , err := encodeRequest (requestID , methodName , params )
89104 if err != nil {
90105 return err
91106 }
@@ -98,12 +113,12 @@ func (c *client) Call(ctx context.Context, methodName string, params interface{}
98113 return decodeResponse (resp , result )
99114}
100115
101- func encodeRequest (method string , args interface {}) ([]byte , error ) {
116+ func encodeRequest (id * json. RawMessage , method string , args interface {}) ([]byte , error ) {
102117 return json .Marshal (& Request {
103118 Version : protocolVersionStr ,
104119 Method : method ,
105120 Params : args ,
106- Id : uint64 ( rand . Int63 ()) ,
121+ Id : id ,
107122 })
108123}
109124
@@ -131,4 +146,4 @@ func decodeResponse(r []byte, reply interface{}) error {
131146 }
132147
133148 return json .Unmarshal (* resp .Result , reply )
134- }
149+ }
0 commit comments