Skip to content

Instantly share code, notes, and snippets.

@nicwest
Created September 24, 2015 14:19
Show Gist options
  • Save nicwest/dd014688600ba8d39bf6 to your computer and use it in GitHub Desktop.
Save nicwest/dd014688600ba8d39bf6 to your computer and use it in GitHub Desktop.
package main
import (
"github.com/gorilla/rpc/v2"
"github.com/gorilla/rpc/v2/json"
"log"
"net/http"
)
type MathArgs struct {
Numbers []int `json:"numbers"`
}
type MathReply struct {
Value int
}
type MathService struct{}
func (h *MathService) Sum(r *http.Request, args *MathArgs, reply *MathReply) error {
var v int
for _, num := range args.Numbers {
v = v + num
}
reply.Value = v
return nil
}
func (h *MathService) Subtract(r *http.Request, args *MathArgs, reply *MathReply) error {
v := args.Numbers[0]
for _, num := range args.Numbers[1:] {
v = v - num
}
reply.Value = v
return nil
}
func main() {
s := rpc.NewServer()
s.RegisterCodec(json.NewCodec(), "application/json")
s.RegisterService(new(MathService), "Math")
http.Handle("/rpc", s)
log.Fatal(http.ListenAndServe(":8888", nil))
}
[
{"jsonrpc": "2.0", "method": "Math.Sum", "params": [{"Numbers": [1,2,4]}], "id": "1"},
{"foo": "boo"},
{"jsonrpc": "2.0", "method": "Math.Subtract", "params": [{"Numbers": [42,23]}], "id": "2"}
]
@nicwest
Copy link
Author

nicwest commented Sep 24, 2015

$rpcexample % curl -X POST -H "Content-Type: application/json" -d "@rpctest.json" http://localhost:8888/rpc
{"result":null,"error":"json: cannot unmarshal array into Go value of type json.serverRequest","id":null}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment