1
0
Fork 0
mirror of https://github.com/sourcegraph/jsonrpc2.git synced 2026-06-16 04:04:56 +02:00

Add a way to specify more non-standard-compliant fields to Request (#50)

This change introduces `ExtraField`, a `CallOption` that can add
arbitrary fields to the top-level JSON-RPC Request message.
This commit is contained in:
lhchavez 2021-08-04 05:45:59 -07:00 committed by GitHub
parent 5cdc7d6ccd
commit d6ac66e24f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 159 additions and 32 deletions

View file

@ -90,3 +90,53 @@ func TestStringID(t *testing.T) {
t.Fatal(err)
}
}
func TestExtraField(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a, b := inMemoryPeerConns()
defer a.Close()
defer b.Close()
handler := handlerFunc(func(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) {
replyWithError := func(msg string) {
respErr := &jsonrpc2.Error{Code: jsonrpc2.CodeInvalidRequest, Message: msg}
if err := conn.ReplyWithError(ctx, req.ID, respErr); err != nil {
t.Error(err)
}
}
var sessionID string
for _, field := range req.ExtraFields {
if field.Name != "sessionId" {
continue
}
var ok bool
sessionID, ok = field.Value.(string)
if !ok {
t.Errorf("\"sessionId\" is not a string: %v", field.Value)
}
}
if sessionID == "" {
replyWithError("sessionId must be set")
return
}
if sessionID != "session" {
replyWithError("sessionId has the wrong value")
return
}
if err := conn.Reply(ctx, req.ID, "ok"); err != nil {
t.Error(err)
}
})
connA := jsonrpc2.NewConn(ctx, jsonrpc2.NewBufferedStream(a, jsonrpc2.VSCodeObjectCodec{}), handler)
connB := jsonrpc2.NewConn(ctx, jsonrpc2.NewBufferedStream(b, jsonrpc2.VSCodeObjectCodec{}), noopHandler{})
defer connA.Close()
defer connB.Close()
var res string
if err := connB.Call(ctx, "f", nil, &res, jsonrpc2.ExtraField("sessionId", "session")); err != nil {
t.Fatal(err)
}
}