server.go 1.06 KB
Newer Older
Lei Li's avatar
Lei Li committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package main

import (
	"context"
	"fmt"
	"time"

	pb "linkfog.com/pluginx/proto"
	"linkfog.com/public/lib/l"
)

type PluginFunc func(req *pb.Req) (*pb.Res, error)

type pluginServer struct {
	pb.UnimplementedPluginServer

	pluginName  string
	pluginFuncs map[string]PluginFunc
}

func newServer(pluginName string, pluginFuncs map[string]PluginFunc) *pluginServer {
	s := &pluginServer{
		pluginName:  pluginName,
		pluginFuncs: pluginFuncs,
	}
	return s
}

func (s *pluginServer) Call(ctx context.Context, req *pb.Req) (*pb.Res, error) {
	pluginName := req.Header.To
	funcName := req.Header.Func
	if pluginName != s.pluginName {
		return nil, fmt.Errorf("mismatch plugin name %s, %s expected", pluginName, s.pluginName)
	}

	pluginFunc, ok := s.pluginFuncs[funcName]
	if !ok {
		return nil, fmt.Errorf("unknown plugin func %s", funcName)
	}

	start := time.Now()
	res, err := pluginFunc(req)
	if err != nil {
		return res, fmt.Errorf("call plugin func %s err: %v", funcName, err)
	}
	l.Infof("call plugin func %s success, cost: %v", funcName, time.Since(start))
	return res, nil
}