github.com/tickoalcantara12/micro/v3@v3.0.0-20221007104245-9d75b9bcbab9/plugin/manager.go (about)

     1  package plugin
     2  
     3  import (
     4  	"fmt"
     5  	"sync"
     6  )
     7  
     8  const defaultModule = "micro"
     9  
    10  type manager struct {
    11  	sync.Mutex
    12  	plugins    map[string][]Plugin
    13  	registered map[string]map[string]bool
    14  }
    15  
    16  var (
    17  	// global plugin manager
    18  	defaultManager = newManager()
    19  )
    20  
    21  func newManager() *manager {
    22  	return &manager{
    23  		plugins:    make(map[string][]Plugin),
    24  		registered: make(map[string]map[string]bool),
    25  	}
    26  }
    27  
    28  func (m *manager) Plugins(opts ...PluginOption) []Plugin {
    29  	options := PluginOptions{Module: defaultModule}
    30  	for _, o := range opts {
    31  		o(&options)
    32  	}
    33  
    34  	m.Lock()
    35  	defer m.Unlock()
    36  
    37  	if plugins, ok := m.plugins[options.Module]; ok {
    38  		return plugins
    39  	}
    40  	return []Plugin{}
    41  }
    42  
    43  func (m *manager) Register(plugin Plugin, opts ...PluginOption) error {
    44  	options := PluginOptions{Module: defaultModule}
    45  	for _, o := range opts {
    46  		o(&options)
    47  	}
    48  
    49  	m.Lock()
    50  	defer m.Unlock()
    51  
    52  	name := plugin.String()
    53  
    54  	if reg, ok := m.registered[options.Module]; ok && reg[name] {
    55  		return fmt.Errorf("Plugin with name %s already registered", name)
    56  	}
    57  
    58  	if _, ok := m.registered[options.Module]; !ok {
    59  		m.registered[options.Module] = map[string]bool{name: true}
    60  	} else {
    61  		m.registered[options.Module][name] = true
    62  	}
    63  
    64  	if _, ok := m.plugins[options.Module]; ok {
    65  		m.plugins[options.Module] = append(m.plugins[options.Module], plugin)
    66  	} else {
    67  		m.plugins[options.Module] = []Plugin{plugin}
    68  	}
    69  
    70  	return nil
    71  }
    72  
    73  func (m *manager) isRegistered(plugin Plugin, opts ...PluginOption) bool {
    74  	options := PluginOptions{Module: defaultModule}
    75  	for _, o := range opts {
    76  		o(&options)
    77  	}
    78  
    79  	m.Lock()
    80  	defer m.Unlock()
    81  
    82  	if _, ok := m.registered[options.Module]; !ok {
    83  		return false
    84  	}
    85  
    86  	return m.registered[options.Module][plugin.String()]
    87  }