Created
December 9, 2016 05:18
-
-
Save osamingo/45bc0c3cef410ec0acab2d09fefac0f1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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