1
0
Fork 0

Unmarshall JSON using user func

This commit is contained in:
Gregory Eremin 2015-01-19 18:22:45 +07:00
parent e234dfaca4
commit cab1a1ad69
3 changed files with 20 additions and 14 deletions

View File

@ -53,11 +53,7 @@ func (c *config) dump() ([]byte, error) {
return out.Bytes(), nil return out.Bytes(), nil
} }
func (c *config) load(b []byte) (err error) { // TODO: function is too heavy, needs refactor
return
}
// TODO: function draft, needs refactor
func (c *config) meta(prefix string) []*configField { func (c *config) meta(prefix string) []*configField {
var ( var (
fields = []*configField{} fields = []*configField{}

View File

@ -1,6 +1,7 @@
package main package main
import ( import (
"encoding/json"
"flag" "flag"
"github.com/localhots/confection" "github.com/localhots/confection"
@ -33,6 +34,12 @@ func main() {
conf := Config{ conf := Config{
DatabaseConfig: DatabaseConfig{}, DatabaseConfig: DatabaseConfig{},
} }
manager := confection.New(conf) manager := confection.New(conf, func(b []byte) interface{} {
var newConf Config
if err := json.Unmarshal(b, &newConf); err != nil {
panic(err)
}
return newConf
})
manager.StartServer() manager.StartServer()
} }

View File

@ -7,9 +7,10 @@ import (
type ( type (
Manager struct { Manager struct {
mux *sync.Mutex mux *sync.Mutex
conf *config conf *config
file *configFile file *configFile
unmarshaller func([]byte) interface{}
} }
) )
@ -23,7 +24,7 @@ func SetupFlags() {
flag.IntVar(&serverPort, "config-port", 5050, "Config manager http port") flag.IntVar(&serverPort, "config-port", 5050, "Config manager http port")
} }
func New(conf interface{}) *Manager { func New(conf interface{}, unmarshaller func([]byte) interface{}) *Manager {
mgr := &Manager{ mgr := &Manager{
mux: &sync.Mutex{}, mux: &sync.Mutex{},
conf: &config{ conf: &config{
@ -32,6 +33,7 @@ func New(conf interface{}) *Manager {
file: &configFile{ file: &configFile{
path: configPath, path: configPath,
}, },
unmarshaller: unmarshaller,
} }
mgr.bootstrap() mgr.bootstrap()
@ -57,10 +59,7 @@ func (m *Manager) bootstrap() {
panic(err) panic(err)
} }
err = m.conf.load(b) m.importJson(b)
if err != nil {
panic(err)
}
} else { } else {
b, err := m.conf.dump() b, err := m.conf.dump()
if err != nil { if err != nil {
@ -73,3 +72,7 @@ func (m *Manager) bootstrap() {
} }
} }
} }
func (m *Manager) importJson(b []byte) {
m.conf.config = m.unmarshaller(b)
}