gitee.com/h79/goutils@v1.22.10/plugins/plugins.go (about)

     1  package plugins
     2  
     3  import (
     4  	"context"
     5  	"sync"
     6  )
     7  
     8  const (
     9  	KAlarm = "alarm"
    10  )
    11  
    12  type Command struct {
    13  	Cmd  string
    14  	Data interface{}
    15  }
    16  
    17  type Data struct {
    18  	Error error
    19  	Data  interface{}
    20  }
    21  type Chan chan Data
    22  
    23  type Plugin interface {
    24  	// Do
    25  	// name is plugin's name
    26  	// key parameter is custom defined
    27  	// d parameter is can use Command or custom
    28  	// return is custom
    29  	Do(ctx context.Context, key string, d interface{}) (interface{}, error)
    30  	DoChan(ctx context.Context, key string, d interface{}) (Chan, error)
    31  }
    32  
    33  type Plugins struct {
    34  	locker sync.RWMutex
    35  	plus   map[string]Plugin
    36  }
    37  
    38  var plugins *Plugins
    39  var def *defaultPlugin
    40  
    41  func init() {
    42  	def = &defaultPlugin{}
    43  	plugins = &Plugins{
    44  		plus: make(map[string]Plugin),
    45  	}
    46  }
    47  
    48  func Get(name string) Plugin {
    49  	plugins.locker.RLock()
    50  	defer plugins.locker.RUnlock()
    51  
    52  	if p, exist := plugins.plus[name]; exist {
    53  		return p
    54  	}
    55  	return def
    56  }
    57  
    58  func Add(name string, p Plugin) {
    59  	plugins.locker.Lock()
    60  	defer plugins.locker.Unlock()
    61  	plugins.plus[name] = p
    62  }
    63  
    64  func Remove(name string) {
    65  	plugins.locker.Lock()
    66  	defer plugins.locker.Unlock()
    67  	delete(plugins.plus, name)
    68  }
    69  
    70  func Do(name string, ctx context.Context, key string, d interface{}) (interface{}, error) {
    71  	p := Get(name)
    72  	return p.Do(ctx, key, d)
    73  }
    74  
    75  func DoChan(name string, ctx context.Context, key string, d interface{}) (Chan, error) {
    76  	p := Get(name)
    77  	return p.DoChan(ctx, key, d)
    78  }
    79  
    80  // DoWithError 只关心error
    81  func DoWithError(name string, ctx context.Context, key string, d interface{}) error {
    82  	_, err := Do(name, ctx, key, d)
    83  	return err
    84  }