From c95a4dea67ada6781226379741c73c2362306215 Mon Sep 17 00:00:00 2001 From: Gregory Eremin Date: Wed, 11 Feb 2015 16:03:47 +0700 Subject: [PATCH] Unit package holds all unit logic --- core/units.go | 39 --------------------------------------- unit/parser.go | 41 +++++++++++++++++++++++++++++++++++++++++ unit/unit.go | 23 +++++++++++++++++++---- 3 files changed, 60 insertions(+), 43 deletions(-) delete mode 100644 core/units.go create mode 100644 unit/parser.go diff --git a/core/units.go b/core/units.go deleted file mode 100644 index 9929772..0000000 --- a/core/units.go +++ /dev/null @@ -1,39 +0,0 @@ -package core - -import ( - "encoding/json" - "io/ioutil" - "os" - - "github.com/localhots/yeast/impl" - "github.com/localhots/yeast/unit" -) - -var ( - Units = map[string]Caller{} -) - -func LoadUnits() { - f, err := os.Open(Conf().UnitsConfig) - if err != nil { - panic("Failed to open units config: " + Conf().UnitsConfig) - } - b, err := ioutil.ReadAll(f) - if err != nil { - panic("Failed to parse units config: " + Conf().UnitsConfig) - } - - var conf map[string]map[string]interface{} - json.Unmarshal(b, &conf) - - for name, meta := range conf { - // Check for unit implementation and create a unit if there is none - if imp := impl.New(meta["impl"].(string)); imp != nil { - Units[name] = imp - } else { - Units[name] = &unit.Unit{ - Name: name, - } - } - } -} diff --git a/unit/parser.go b/unit/parser.go new file mode 100644 index 0000000..8ef46b9 --- /dev/null +++ b/unit/parser.go @@ -0,0 +1,41 @@ +package unit + +import ( + "encoding/json" + "io/ioutil" + "os" +) + +var ( + units = map[string]*Unit{} +) + +func LoadUnits(path string) { + f, err := os.Open(path) + if err != nil { + panic("Failed to open units config: " + path) + } + b, err := ioutil.ReadAll(f) + if err != nil { + panic("Failed to parse units config: " + path) + } + + var conf map[string]map[string]interface{} + json.Unmarshal(b, &conf) + + for name, meta := range conf { + units[name] = &Unit{ + Name: name, + Impl: meta["impl"].(string), + Config: meta["config"], + } + } +} + +func Units() []string { + list := []string{} + for name, _ := range units { + list = append(list, name) + } + return list +} diff --git a/unit/unit.go b/unit/unit.go index 8d8c4d5..4764b18 100644 --- a/unit/unit.go +++ b/unit/unit.go @@ -5,17 +5,32 @@ import ( "fmt" "net" "strings" + + "github.com/localhots/yeast/impl" ) type ( Unit struct { - Name string + Name string + Impl string + Config interface{} + } + Caller interface { + Call([]byte) ([]byte, error) + Units() []string } ) -func New(name string) *Unit { - return &Unit{ - Name: name, +func New(name string) Caller { + if u, ok := units[name]; ok { + // Check for unit implementation and create a unit if there is none + if imp := impl.New(u.Impl); imp != nil { + return imp + } else { + return u + } + } else { + return nil } }