isle/go/daemon/jsonrpc2/client_rw.go
Brian Picciano 16aca610b4 Add multi-network support to daemon
It's still not possible to pick a network from the command-line, so this
is a bit broken, but the daemon component should handle it correctly at
least.
2024-09-23 19:04:14 +02:00

40 lines
795 B
Go

package jsonrpc2
import (
"context"
"encoding/json"
"fmt"
"io"
)
type rwClient struct {
enc *json.Encoder
dec *json.Decoder
}
// NewReadWriterClient returns a Client which will use the given ReadWriter to
// perform requests.
func NewReadWriterClient(rw io.ReadWriter) Client {
return rwClient{json.NewEncoder(rw), json.NewDecoder(rw)}
}
func (c rwClient) Call(
ctx context.Context, rcv any, method string, args ...any,
) error {
id, err := encodeRequest(ctx, c.enc, method, args)
if err != nil {
return fmt.Errorf("encoding request: %w", err)
}
resID, err := decodeResponse(c.dec, rcv)
if err != nil {
return fmt.Errorf("decoding response: %w", err)
} else if resID != id {
return fmt.Errorf(
"expected response with ID %q, got %q", id, resID,
)
}
return nil
}