aboutsummaryrefslogtreecommitdiff
path: root/examples/http/main.go
blob: 5c24867aad0fe5cf88b15b037127b82ba93deea1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package main

import (
	"context"
	"errors"
	"net/http"

	httpRPC "go.neonxp.dev/jsonrpc2/http"
	"go.neonxp.dev/jsonrpc2/rpc"
)

func main() {
	s := httpRPC.New()

	s.Register("multiply", rpc.Wrap(Multiply))
	s.Register("divide", rpc.Wrap(Divide))

	http.ListenAndServe(":8000", s)
}

func Multiply(ctx context.Context, args *Args) (int, error) {
	return args.A * args.B, nil
}

func Divide(ctx context.Context, args *Args) (*Quotient, error) {
	if args.B == 0 {
		return nil, errors.New("divide by zero")
	}
	quo := new(Quotient)
	quo.Quo = args.A / args.B
	quo.Rem = args.A % args.B
	return quo, nil
}

type Args struct {
	A int `json:"a"`
	B int `json:"b"`
}

type Quotient struct {
	Quo int `json:"quo"`
	Rem int `json:"rem"`
}