Skip to content

Commit

Permalink
Clean up handler examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Dec 4, 2021
1 parent b2a1d11 commit acbe9bb
Showing 1 changed file with 42 additions and 16 deletions.
58 changes: 42 additions & 16 deletions handler/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,30 +69,56 @@ func ExampleObj_unmarshal() {
// uid=501, name="P. T. Barnum"
}

func ExamplePositional() {
func ExamplePositional_object() {
fn := func(ctx context.Context, name string, age int, isOld bool) error {
fmt.Printf("%s is %d (is old: %v)\n", name, age, isOld)
return nil
}
call := handler.NewPos(fn, "name", "age", "isOld")

req, err := jrpc2.ParseRequests([]byte(`
{
"jsonrpc": "2.0",
"id": 1,
"method": "foo",
"params": {
"name": "Dennis",
"age": 37,
"isOld": false
}
}`))
if err != nil {
log.Fatalf("Parse: %v", err)
}
if _, err := call(context.Background(), req[0]); err != nil {
req := mustParseReq(`{
"jsonrpc": "2.0",
"id": 1,
"method": "foo",
"params": {
"name": "Dennis",
"age": 37,
"isOld": false
}
}`)
if _, err := call(context.Background(), req); err != nil {
log.Fatalf("Call: %v", err)
}
// Output:
// Dennis is 37 (is old: false)
}

func ExamplePositional_array() {
fn := func(ctx context.Context, name string, age int, isOld bool) error {
fmt.Printf("%s is %d (is old: %v)\n", name, age, isOld)
return nil
}
call := handler.NewPos(fn, "name", "age", "isOld")

req := mustParseReq(`{
"jsonrpc": "2.0",
"id": 1,
"method": "foo",
"params": ["Marvin", 973000, true]
}`)
if _, err := call(context.Background(), req); err != nil {
log.Fatalf("Call: %v", err)
}
// Output:
// Marvin is 973000 (is old: true)
}

func mustParseReq(s string) *jrpc2.Request {
reqs, err := jrpc2.ParseRequests([]byte(s))
if err != nil {
log.Fatalf("ParseRequests: %v", err)
} else if len(reqs) == 0 {
log.Fatal("ParseRequests: empty result")
}
return reqs[0]
}

0 comments on commit acbe9bb

Please sign in to comment.