package shared import ( "eta/eta_chart_lib/models/data_manage/chart_theme" "github.com/hashicorp/go-plugin" "net/rpc" ) type ChartDataResp struct { DataList []int } // 定义插件接口,即插件对外暴露的接口 // ChartInterface is the interface that we're exposing as a plugin. type ChartInterface interface { GetChartData(int) ChartDataResp GetChartThemeConfig(chartThemeId, source, chartType int) (chartTheme chart_theme.ChartTheme, err error) } // 定义一个rpc客户端,并实现接口里的方法 // Here is an implementation that talks over RPC type ChartRpc struct { client *rpc.Client } // ChartRpc客户端从ChartRpcServer rpc服务器端调用GetChartData方法 func (g *ChartRpc) GetChartData(chartId int) ChartDataResp { var resp ChartDataResp err := g.client.Call("Plugin.GetChartData", chartId, &resp) if err != nil { // You usually want your interfaces to return errors. If they don't, // there isn't much other choice here. panic(err) } return resp } // ChartRpc客户端从ChartRpcServer rpc服务器端调用GetChartThemeConfig方法 func (g *ChartRpc) GetChartThemeConfig(chartThemeId, source, chartType int) (chartTheme chart_theme.ChartTheme, err error) { args := make(map[string]interface{}) args["chartThemeId"] = chartThemeId args["source"] = source args["chartType"] = chartType err = g.client.Call("Plugin.GetChartThemeConfig", args, &chartTheme) if err != nil { // You usually want your interfaces to return errors. If they don't, // there isn't much other choice here. //panic(err) return } return } // ChartRpcServer是一个rpc服务器,用于RPC通信,该服务器与ChartRpc进行通信,并符合net/rpc包的要求。 // Here is the RPC server that ChartRpc talks to, conforming to // the requirements of net/rpc type ChartRpcServer struct { Impl ChartInterface } // 定义服务方法并注册到 RPC 服务器 func (s *ChartRpcServer) GetChartData(args int, resp *ChartDataResp) error { *resp = s.Impl.GetChartData(args) return nil } func (s *ChartRpcServer) GetChartThemeConfig(args map[string]interface{}, resp *chart_theme.ChartTheme) error { var err error *resp, err = s.Impl.GetChartThemeConfig(args["chartThemeId"].(int), args["source"].(int), args["chartType"].(int)) return err } // 实现了plugin.Plugin接口的结构体,plugin.Plugin接口要求实现两个方法:Server和Client。 // Server 方法:此方法需要返回一个RPC服务器实例,这个服务器将负责处理来自客户端的RPC调用。 // Client 方法:此方法需要返回一个实现了特定接口的客户端实例,这个客户端将用于向RPC服务器发送请求并接收响应。 // This is the implementation of plugin.Plugin so we can serve/consume this // // This has two methods: Server must return an RPC server for this plugin // type. We construct a GreeterRPCServer for this. // // Client must return an implementation of our interface that communicates // over an RPC client. We return GreeterRPC for this. // // Ignore MuxBroker. That is used to create more multiplexed streams on our // plugin connection and is a more advanced use case. type ChartPlugin struct { Impl ChartInterface } func (p *ChartPlugin) Server(*plugin.MuxBroker) (interface{}, error) { return &ChartRpcServer{Impl: p.Impl}, nil } func (p *ChartPlugin) Client(broker *plugin.MuxBroker, c *rpc.Client) (interface{}, error) { return &ChartRpc{client: c}, nil }