Slide 37
Slide 37 text
JSON-RPC by osamingo/jsonrpc
37
1 package main
2
3 import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "log"
8 "net/http"
9
10 "github.com/osamingo/jsonrpc"
11 )
12
13 type (
14 MultiplyParams struct {
15 A, B int
16 }
17 MultiplyResult struct {
18 Result int
19 }
20 )
21
22 var _ jsonrpc.Func = Multiply
23
24 func Multiply(c context.Context, params *json.RawMessage) (interface{}, *jsonrpc.Error) {
25 var p MultiplyParams
26 if err := jsonrpc.Unmarshal(params, &p); err != nil {
27 return nil, err
28 }
29 return MultiplyResult{
30 Result: p.A * p.B,
31 }, nil
32 }
33
34 func init() {
35 jsonrpc.RegisterMethod("Arithmetic.Multiply", Multiply, MultiplyParams{}, MultiplyResult{})
36 http.HandleFunc("/jrpc", jsonrpc.Handler)
37 http.HandleFunc("/jrpc/debug", jsonrpc.DebugHandler)
38 go http.ListenAndServe(":8080", nil)
39 }
40
41 func main() {
42 resp, err := http.Post("http://localhost:8080/jrpc", "application/json",
43 bytes.NewBufferString(`{
44 "jsonrpc": "2.0",
45 "method": "Arithmetic.Multiply",
46 "params": {
47 "A": 15,
48 "B": 15
49 },
50 "id": 456
51 }`))
52 if err != nil {
53 log.Fatalln(err)
54 }
55 defer resp.Body.Close()
56 var body jsonrpc.Response
57 if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
58 log.Fatalln(err)
59 }
60 log.Println(body.Result.(map[string]interface{})["Result"])
61 }
https://git.io/v1Vew