registry.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. package flow
  2. import "reflect"
  3. // Global
  4. var (
  5. globalRegistry = NewRegistry()
  6. Register = globalRegistry.Register
  7. )
  8. // Registry function registry
  9. type Registry struct {
  10. data map[string]interface{}
  11. }
  12. // NewRegistry creates a new registry
  13. func NewRegistry() *Registry {
  14. return &Registry{map[string]interface{}{}}
  15. }
  16. //Register should be a func only register
  17. func (r *Registry) Register(name string, v interface{}) error {
  18. fntyp := reflect.TypeOf(v)
  19. if fntyp.Kind() != reflect.Func {
  20. return ErrNotAFunc
  21. }
  22. if fntyp.NumOut() == 0 {
  23. return ErrOutput
  24. }
  25. r.data[name] = v
  26. return nil
  27. }
  28. // Get an entry
  29. func (r *Registry) Get(name string, params ...interface{}) (interface{}, error) {
  30. v, ok := r.data[name]
  31. if !ok {
  32. return nil, ErrNotFound
  33. }
  34. // We already know this is a function
  35. // and that returns 1 or more values
  36. vtyp := reflect.TypeOf(v)
  37. if vtyp.Out(0).Kind() == reflect.Func {
  38. fparam := make([]reflect.Value, len(params))
  39. for i := range params {
  40. fparam[i] = reflect.ValueOf(params[i])
  41. }
  42. // Call the func and return the thing
  43. v = reflect.ValueOf(v).Call(fparam)[0].Interface()
  44. }
  45. return v, nil
  46. }
  47. // opFunc creator
  48. /*type opFactory func() *opFunc
  49. // Registry of operator factory functions
  50. type Registry struct {
  51. opFactory map[string]opFactory
  52. }
  53. // NewRegistry Creates a new registry
  54. func NewRegistry() *Registry {
  55. r := &Registry{
  56. map[string]opFactory{},
  57. }
  58. return r
  59. }
  60. // Register a new operator
  61. func (r *Registry) Register(name string, fn interface{}) error {
  62. fntyp := reflect.TypeOf(fn)
  63. if fntyp.Kind() != reflect.Func {
  64. return ErrNotFunc
  65. }
  66. if fntyp.NumOut() == 0 {
  67. return ErrOutput
  68. }
  69. // Directly add this factory?
  70. if f, ok := fn.(opFactory); ok {
  71. r.opFactory[name] = f
  72. }
  73. // Constructor for func
  74. // opFunc creator?
  75. cfn := func() *opFunc {
  76. op := &opFunc{
  77. executor: fn,
  78. }
  79. return op
  80. }
  81. // Create function factory for function?
  82. //Create factory from func
  83. r.opFactory[name] = cfn
  84. //return nil
  85. return nil
  86. }
  87. //Get a New Operation
  88. func (r *Registry) Get(name string) (*opFunc, error) {
  89. createOP, ok := r.opFactory[name]
  90. if !ok {
  91. return nil, errors.New("Does not exists")
  92. }
  93. return createOP(), nil
  94. }*/