trpc.group/trpc-go/trpc-go@v1.0.3/plugin/plugin.go (about)

     1  //
     2  //
     3  // Tencent is pleased to support the open source community by making tRPC available.
     4  //
     5  // Copyright (C) 2023 THL A29 Limited, a Tencent company.
     6  // All rights reserved.
     7  //
     8  // If you have downloaded a copy of the tRPC source code from Tencent,
     9  // please note that tRPC source code is licensed under the  Apache 2.0 License,
    10  // A copy of the Apache 2.0 License is included in this file.
    11  //
    12  //
    13  
    14  // Package plugin implements a general plugin factory system which provides plugin registration and loading.
    15  // It is mainly used when certain plugins must be loaded by configuration.
    16  // This system is not supposed to register plugins that do not rely on configuration like codec. Instead, plugins
    17  // that do not rely on configuration should be registered by calling methods in certain packages.
    18  package plugin
    19  
    20  var plugins = make(map[string]map[string]Factory) // plugin type => { plugin name => plugin factory }
    21  
    22  // Factory is the interface for plugin factory abstraction.
    23  // Custom Plugins need to implement this interface to be registered as a plugin with certain type.
    24  type Factory interface {
    25  	// Type returns type of the plugin, i.e. selector, log, config, tracing.
    26  	Type() string
    27  	// Setup loads plugin by configuration.
    28  	// The data structure of the configuration of the plugin needs to be defined in advance。
    29  	Setup(name string, dec Decoder) error
    30  }
    31  
    32  // Decoder is the interface used to decode plugin configuration.
    33  type Decoder interface {
    34  	Decode(cfg interface{}) error // the input param is the custom configuration of the plugin
    35  }
    36  
    37  // Register registers a plugin factory.
    38  // Name of the plugin should be specified.
    39  // It is supported to register instances which are the same implementation of plugin Factory
    40  // but use different configuration.
    41  func Register(name string, f Factory) {
    42  	factories, ok := plugins[f.Type()]
    43  	if !ok {
    44  		factories = make(map[string]Factory)
    45  		plugins[f.Type()] = factories
    46  	}
    47  	factories[name] = f
    48  }
    49  
    50  // Get returns a plugin Factory by its type and name.
    51  func Get(typ string, name string) Factory {
    52  	return plugins[typ][name]
    53  }