forked from luraproject/lura
/
plugin.go
98 lines (83 loc) · 2.09 KB
/
plugin.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package plugin
import (
"fmt"
"io/ioutil"
"plugin"
"strings"
"github.com/khvysofq/krakend/config"
)
// Plugin is the interface of the loaded plugins
type Plugin interface {
Lookup(name string) (plugin.Symbol, error)
}
// Load loads all the plugins in pluginFolder with pattern in its filename.
// It returns the number of plugins loaded and an error if something goes wrong.
func Load(cfg config.Plugin, reg *Register) (int, error) {
plugins, err := scan(cfg.Folder, cfg.Pattern)
if err != nil {
return 0, err
}
return load(plugins, reg)
}
func scan(folder, pattern string) ([]string, error) {
files, err := ioutil.ReadDir(folder)
if err != nil {
return []string{}, err
}
plugins := []string{}
for _, file := range files {
if !file.IsDir() && strings.Contains(file.Name(), pattern) {
plugins = append(plugins, folder+file.Name())
}
}
return plugins, nil
}
func load(plugins []string, reg *Register) (int, error) {
errors := []error{}
loadedPlugins := 0
for k, pluginName := range plugins {
if err := open(pluginName, reg); err != nil {
errors = append(errors, fmt.Errorf("opening plugin %d (%s): %s", k, pluginName, err.Error()))
continue
}
loadedPlugins++
}
if len(errors) > 0 {
return loadedPlugins, loaderError{errors}
}
return loadedPlugins, nil
}
func open(pluginName string, reg *Register) (err error) {
defer func() {
if r := recover(); r != nil {
var ok bool
err, ok = r.(error)
if !ok {
err = fmt.Errorf("%v", r)
}
}
}()
var p Plugin
p, err = pluginOpener(pluginName)
if err != nil {
return
}
err = reg.Register(p)
return
}
// pluginOpener keeps the plugin open function in a var for easy testing
var pluginOpener = defaultPluginOpener
func defaultPluginOpener(name string) (Plugin, error) {
return plugin.Open(name)
}
type loaderError struct {
errors []error
}
// Error implements the error interface
func (l loaderError) Error() string {
msgs := make([]string, len(l.errors))
for i, err := range l.errors {
msgs[i] = err.Error()
}
return fmt.Sprintf("plugin loader found %d error(s): \n%s", len(msgs), strings.Join(msgs, "\n"))
}