forked from trpc-group/trpc-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.go
53 lines (47 loc) · 2.02 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
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
// Package plugin implements a general plugin factory system which provides plugin registration and loading.
// It is mainly used when certain plugins must be loaded by configuration.
// This system is not supposed to register plugins that do not rely on configuration like codec. Instead, plugins
// that do not rely on configuration should be registered by calling methods in certain packages.
package plugin
var plugins = make(map[string]map[string]Factory) // plugin type => { plugin name => plugin factory }
// Factory is the interface for plugin factory abstraction.
// Custom Plugins need to implement this interface to be registered as a plugin with certain type.
type Factory interface {
// Type returns type of the plugin, i.e. selector, log, config, tracing.
Type() string
// Setup loads plugin by configuration.
// The data structure of the configuration of the plugin needs to be defined in advance。
Setup(name string, dec Decoder) error
}
// Decoder is the interface used to decode plugin configuration.
type Decoder interface {
Decode(cfg interface{}) error // the input param is the custom configuration of the plugin
}
// Register registers a plugin factory.
// Name of the plugin should be specified.
// It is supported to register instances which are the same implementation of plugin Factory
// but use different configuration.
func Register(name string, f Factory) {
factories, ok := plugins[f.Type()]
if !ok {
factories = make(map[string]Factory)
plugins[f.Type()] = factories
}
factories[name] = f
}
// Get returns a plugin Factory by its type and name.
func Get(typ string, name string) Factory {
return plugins[typ][name]
}