github.com/ngicks/gokugen@v0.0.5/impl/work_registry/prefix.go (about) 1 package workregistry 2 3 import ( 4 "strings" 5 "sync" 6 7 "github.com/ngicks/gokugen/cron" 8 ) 9 10 // Prefix is simple prefixer of WorkRegistry. 11 // It stores registries with prefix associated to them. 12 // 13 // Main purpose of Prefix is mixing Cli and other manually registered functions. 14 // e.g. prefix cli commands with `cli:` like `cli:ls` and other function with `gofunc:` 15 type Prefix struct { 16 mu sync.Mutex 17 others map[string]cron.WorkRegistry 18 } 19 20 type PrefixOption func(p *Prefix) *Prefix 21 22 // PrefixAddMap is option to NewPrefix. 23 // PrefixAddMap adds regitries by passing map. 24 // Key must be prefix string. Value must be work registry paired to prefix. 25 func PrefixAddMap(m map[string]cron.WorkRegistry) PrefixOption { 26 return func(p *Prefix) *Prefix { 27 for k, v := range m { 28 p.others[k] = v 29 } 30 return p 31 } 32 } 33 34 func PrefixAddRegistry(prefix string, registry cron.WorkRegistry) PrefixOption { 35 return func(p *Prefix) *Prefix { 36 p.others[prefix] = registry 37 return p 38 } 39 } 40 41 func NewPrefix(options ...PrefixOption) *Prefix { 42 p := &Prefix{ 43 others: make(map[string]cron.WorkRegistry), 44 } 45 for _, opt := range options { 46 p = opt(p) 47 } 48 return p 49 } 50 51 // Load loads work function associated with given prefixedKey. 52 // Load assumes that key is prefixed with known keyword. 53 // It removes prefix and then loads work function from a registry paired with the prefix. 54 func (p *Prefix) Load(prefixedKey string) (value cron.WorkFnWParam, ok bool) { 55 p.mu.Lock() 56 defer p.mu.Unlock() 57 58 for prefix, registry := range p.others { 59 if strings.HasPrefix(prefixedKey, prefix) { 60 return registry.Load(prefixedKey[len(prefix):]) 61 } 62 } 63 return 64 }