Skip to content

Commit

Permalink
Make examples independently runnable.
Browse files Browse the repository at this point in the history
When the examples are run in isolation, for example on godoc.org or a local doc
server, the server doesn't get started unless the setup example is also run.
pull out the setup code to ensure each example is runnable on its own.
  • Loading branch information
creachadair committed Aug 2, 2021
1 parent 2b0cca1 commit a9921c4
Showing 1 changed file with 27 additions and 12 deletions.
39 changes: 27 additions & 12 deletions examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"log"
"strings"
"sync"

"github.com/creachadair/jrpc2"
"github.com/creachadair/jrpc2/channel"
Expand All @@ -19,26 +20,34 @@ var (
ctx = context.Background()
sch, cch = channel.Direct()
cli = jrpc2.NewClient(cch, nil)

setup sync.Once
)

type Msg struct {
Text string `json:"msg"`
}

func startServer() {
setup.Do(func() {
s = jrpc2.NewServer(handler.Map{
"Hello": handler.New(func(ctx context.Context) string {
return "Hello, world!"
}),
"Echo": handler.New(func(_ context.Context, args []json.RawMessage) []json.RawMessage {
return args
}),
"Log": handler.New(func(ctx context.Context, msg Msg) (bool, error) {
fmt.Println("Log:", msg.Text)
return true, nil
}),
}, nil).Start(sch)
})
}

func ExampleNewServer() {
// Construct a new server with methods "Hello" and "Log".
s = jrpc2.NewServer(handler.Map{
"Hello": handler.New(func(ctx context.Context) string {
return "Hello, world!"
}),
"Echo": handler.New(func(_ context.Context, args []json.RawMessage) []json.RawMessage {
return args
}),
"Log": handler.New(func(ctx context.Context, msg Msg) (bool, error) {
fmt.Println("Log:", msg.Text)
return true, nil
}),
}, nil).Start(sch)
startServer()

// We can query the server for its current status information, including a
// list of its methods.
Expand All @@ -52,6 +61,8 @@ func ExampleNewServer() {
}

func ExampleClient_Call() {
startServer()

// var cli = jrpc2.NewClient(cch, nil)
rsp, err := cli.Call(ctx, "Hello", nil)
if err != nil {
Expand All @@ -67,6 +78,8 @@ func ExampleClient_Call() {
}

func ExampleClient_CallResult() {
startServer()

// var cli = jrpc2.NewClient(cch, nil)
var msg string
if err := cli.CallResult(ctx, "Hello", nil, &msg); err != nil {
Expand All @@ -78,6 +91,8 @@ func ExampleClient_CallResult() {
}

func ExampleClient_Batch() {
startServer()

// var cli = jrpc2.NewClient(cch, nil)
rsps, err := cli.Batch(ctx, []jrpc2.Spec{
{Method: "Hello"},
Expand Down

0 comments on commit a9921c4

Please sign in to comment.