1
0
Fork 0

Unit package holds all unit logic

This commit is contained in:
Gregory Eremin 2015-02-11 16:03:47 +07:00
parent 18ca775e02
commit c95a4dea67
3 changed files with 60 additions and 43 deletions

View File

@ -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,
}
}
}
}

41
unit/parser.go Normal file
View File

@ -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
}

View File

@ -5,17 +5,32 @@ import (
"fmt" "fmt"
"net" "net"
"strings" "strings"
"github.com/localhots/yeast/impl"
) )
type ( type (
Unit struct { Unit struct {
Name string Name string
Impl string
Config interface{}
}
Caller interface {
Call([]byte) ([]byte, error)
Units() []string
} }
) )
func New(name string) *Unit { func New(name string) Caller {
return &Unit{ if u, ok := units[name]; ok {
Name: name, // 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
} }
} }