Skip to content

Commit

Permalink
Document reverse calling
Browse files Browse the repository at this point in the history
  • Loading branch information
magik6k committed Jun 6, 2024
1 parent 2b2ff55 commit 938dd3e
Showing 1 changed file with 70 additions and 0 deletions.
70 changes: 70 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,76 @@ if err := client.Add(10); err != nil {
fmt.Printf("Current value: %d\n", client.AddGet(5))
```

### Reverse Calling Feature
The go-jsonrpc library also supports reverse calling, where the server can make calls to the client. This is useful in scenarios where the server needs to notify or request data from the client.

NOTE: Reverse calling only works in websocket mode

#### Example Usage of Reverse Calling

Here is an example demonstrating how to set up reverse calling:

```go
// Define the client handler interface
type ClientHandler struct {
CallOnClient func(int) (int, error)
}

// Define the server handler
type ServerHandler struct {}

func (h *ServerHandler) Call(ctx context.Context) error {
revClient, ok := jsonrpc.ExtractReverseClient[ClientHandler](ctx)
if !ok {
return fmt.Errorf("no reverse client")
}

result, err := revClient.CallOnClient(7) // Multiply by 2 on client
if err != nil {
return fmt.Errorf("call on client: %w", err)
}

if result != 14 {
return fmt.Errorf("unexpected result: %d", result)
}

return nil
}

// Define client handler
type RevCallTestClientHandler struct {
}

func (h *RevCallTestClientHandler) CallOnClient(a int) (int, error) {
return a * 2, nil
}

// Setup server with reverse client capability
rpcServer := jsonrpc.NewServer(jsonrpc.WithReverseClient[ClientHandler]("Client"))
rpcServer.Register("ServerHandler", &ServerHandler{})

testServ := httptest.NewServer(rpcServer)
defer testServ.Close()

// Setup client with reverse call handler
var client struct {
Call func() error
}

closer, err := jsonrpc.NewMergeClient(context.Background(), "ws://"+testServ.Listener.Addr().String(), "ServerHandler", []interface{}{
&client,
}, nil, jsonrpc.WithClientHandler("Client", &RevCallTestClientHandler{}))
if err != nil {
log.Fatalf("Failed to create client: %v", err)
}
defer closer()

// Make a call from the client to the server, which will trigger a reverse call
if err := client.Call(); err != nil {
log.Fatalf("Failed to call server: %v", err)
}
```

## Contribute

PRs are welcome!
Expand Down

0 comments on commit 938dd3e

Please sign in to comment.