Skip to content

Instantly share code, notes, and snippets.

@osamingo
Created December 9, 2016 04:58
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/fee8fc6ac437da9dcf58dd535ab63439 to your computer and use it in GitHub Desktop.
Save osamingo/fee8fc6ac437da9dcf58dd535ab63439 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"log"
"net/http"
"github.com/gorilla/rpc/v2"
"github.com/gorilla/rpc/v2/json2"
)
type (
Arithmetic struct{}
MultiplyArgs struct {
A, B int
}
MultiplyResult struct {
Result int
}
)
func (a *Arithmetic) Multiply(r *http.Request, args *MultiplyArgs, reply *MultiplyResult) error {
reply.Result = args.A * args.B
return nil
}
func init() {
s := rpc.NewServer()
s.RegisterCodec(json2.NewCodec(), "application/json")
arithmetic := &Arithmetic{}
s.RegisterService(arithmetic, "")
http.Handle("/jrpc", s)
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": 10,
"B": 10
},
"id": 123
}`))
if err != nil {
log.Fatalln(err)
}
defer resp.Body.Close()
var ret MultiplyResult
err = json2.DecodeClientResponse(resp.Body, &ret)
if err != nil {
log.Println("aaa")
log.Fatalln(err)
}
log.Println(ret.Result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment