官网
http://www.gorillatoolkit.org/pkg/rpc#subdirs
测试代码
为了更好的说明使用方法,对原文的代码有所修改。
type RPCAPIArguments struct {
Message string
Msg string
}
type RPCAPIResponse struct {
Message string
Masg string
}
type StringService struct{}
func (h *StringService) Length(r *http.Request, arguments *RPCAPIArguments, reply *RPCAPIResponse) error {
Debug(r.Header)
Debug(arguments.Message)
Debug(arguments.Msg)
reply.Message = "Your string is " + fmt.Sprintf("Your string is%d chars long", utf8.RuneCountInString(arguments.Message)) +
"characters long"
reply.Masg = "er"
return nil
}
func f(i *rpc.RequestInfo) {
Debug("fucn")
return
}
func main() {
fmt.Println("Starting service")
// s := rpc.NewServer()
// s.RegisterCodec(json.NewCodec(), "application/json")
// s.RegisterService(new(StringService), "")
s := rpc.NewServer()
s.RegisterCodec(json.NewCodec(), "application/json")
s.RegisterService(new(StringService), "")
s.RegisterAfterFunc(f)
http.Handle("/rpc", s)
http.ListenAndServe(":10000", nil)
}
测试请求
{
"method": "StringService.Length",
"params": [
{
"Message": "Testing therservied",
"Msg": "sbig"
}
],
"id": "3"
}
响应
{
"result": {
"Message": "Your string is Your string is19 chars longcharacters long",
"Masg": "er"
},
"error": null,
"id": "3"
}
说明:
在POST数据中,method指定要远程执行的方法,StringService.Length对应服务器中的StringService类型的Length方法。通过
s.RegisterService(new(StringService), "")
将StringService注册到RPC。
params指定传递的参数,分别对应StringService的两个成员变量 Message,Msg。