JSON-RPC

示例

服务端

package main import ( "github.com/sohaha/zlsgo/znet" ) type Result struct { Num, Ans int } type Cal int func (cal *Cal) Square(num int, result *Result) error { result.Num = num result.Ans = num * num return nil } func main() { r := znet.New() // 注册 RPC 服务 r.Any("/rpc", znet.JSONRPC(map[string]interface{}{ "Cal": new(Cal), }), func(c *znet.Context) { token := c.Request.Header.Get("Authorization") if token != "123456" { // 比如 token 不匹配不允许连接 c.Abort(401) return } }) r.SetAddr(":18181") znet.Run() }
 

客户端

package main import ( "github.com/sohaha/zlsgo/zhttp" "github.com/sohaha/zlsgo/zlog" ) func main() { client, err := zhttp.NewJSONRPC("http://127.0.0.1:18181", "/rpc", func(o *zhttp.JSONRPCOptions) { // 可以设置请求头 o.Header.Add("Authorization", "123456") }) if err != nil { zlog.Error(err) return } type Result struct { Num, Ans int } var result Result err = client.Call("Cal.Square", 12, &result) zlog.Debug(err, result) // 或者 HTTP POST 调用 // res, err := zhttp.Post("http://127.0.0.1:18181/__rpc", zhttp.BodyJSON(map[string]interface{}{ // "method": "Cal.Square", // "params": []int{12}, // "id": 1, // })) }