Skip to content

Instantly share code, notes, and snippets.

@osamingo
Created December 9, 2016 05:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save osamingo/45bc0c3cef410ec0acab2d09fefac0f1 to your computer and use it in GitHub Desktop.
Save osamingo/45bc0c3cef410ec0acab2d09fefac0f1 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"context"
"encoding/json"
"log"
"net/http"
"github.com/osamingo/jsonrpc"
)
type (
MultiplyParams struct {
A, B int
}
MultiplyResult struct {
Result int
}
)
var _ jsonrpc.Func = Multiply
func Multiply(c context.Context, params *json.RawMessage) (interface{}, *jsonrpc.Error) {
var p MultiplyParams
if err := jsonrpc.Unmarshal(params, &p); err != nil {
return nil, err
}
return MultiplyResult{
Result: p.A * p.B,
}, nil
}
func init() {
jsonrpc.RegisterMethod("Arithmetic.Multiply", Multiply, MultiplyParams{}, MultiplyResult{})
http.HandleFunc("/jrpc", jsonrpc.Handler)
http.HandleFunc("/jrpc/debug", jsonrpc.DebugHandler)
go http.ListenAndServe(":8080", nil)
}
func main() {
resp, err := http.Post("http://localhost:8080/jrpc", "application/json",
bytes.NewBufferString(`{
"jsonrpc": "2.0",
"method": "Arithmetic.Multiply",
"params": {
"A": 15,
"B": 15
},
"id": 456
}`))
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
var body jsonrpc.Response
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
log.Fatalln(err)
}
log.Println(body.Result.(map[string]interface{})["Result"])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment