diff --git a/README.md b/README.md index d2406ab..df4f081 100644 --- a/README.md +++ b/README.md @@ -3,9 +3,8 @@ Package jsonrpc2 provides a [Go](https://golang.org) implementation of [JSON-RPC 2.0](http://www.jsonrpc.org/specification). -This package is **experimental** until further notice. - -[**Open the code in Sourcegraph**](https://sourcegraph.com/github.com/sourcegraph/jsonrpc2) +* [Documentation](https://pkg.go.dev/github.com/sourcegraph/jsonrpc2) +* [Open the code in Sourcegraph](https://sourcegraph.com/github.com/sourcegraph/jsonrpc2) ## Known issues diff --git a/example_test.go b/example_test.go new file mode 100644 index 0000000..00f4a57 --- /dev/null +++ b/example_test.go @@ -0,0 +1,64 @@ +package jsonrpc2_test + +import ( + "context" + "fmt" + "log" + "net" + "os" + + "github.com/sourcegraph/jsonrpc2" +) + +func Example() { + ctx := context.Background() + + // Create an in-memory network connection. This connection is used below to + // transport the JSON-RPC messages. However, any io.ReadWriteCloser may be + // used to send/receive JSON-RPC messages. + connA, connB := net.Pipe() + + // The following JSON-RPC connection is both a client and a server. It can + // send requests as well as receive requests. The incoming requests are + // handled by myHandler. + jsonrpcConnA := jsonrpc2.NewConn(ctx, jsonrpc2.NewPlainObjectStream(connA), &myHandler{}) + defer jsonrpcConnA.Close() + + // The following JSON-RPC connection has no handler, meaning that it is + // configured to only be a client. It can send requests and receive the + // responses to those requests, but it will ignore any incoming requests. + jsonrpcConnB := jsonrpc2.NewConn(ctx, jsonrpc2.NewPlainObjectStream(connB), nil) + defer jsonrpcConnB.Close() + + // Send a request from jsonrpcConnB to jsonrpcConnA. The result of a + // successful call is stored in the result variable. + var result string + if err := jsonrpcConnB.Call(ctx, "sayHello", nil, &result); err != nil { + fmt.Fprintln(os.Stderr, err) + return + } + + fmt.Println(result) + + // Output: hello world +} + +// myHandler is the jsonrpc2.Handler used by jsonrpcConnA. +type myHandler struct{} + +// Handle implements the jsonrpc2.Handler interface. +func (h *myHandler) Handle(ctx context.Context, c *jsonrpc2.Conn, r *jsonrpc2.Request) { + switch r.Method { + case "sayHello": + if err := c.Reply(ctx, r.ID, "hello world"); err != nil { + log.Println(err) + return + } + default: + err := &jsonrpc2.Error{Code: jsonrpc2.CodeMethodNotFound, Message: "Method not found"} + if err := c.ReplyWithError(ctx, r.ID, err); err != nil { + log.Println(err) + return + } + } +}