config_manager_go/config.go
2017-04-14 14:27:38 +09:00

132 lines
2.2 KiB
Go

package config_manager_go
import (
"os"
"log"
"io/ioutil"
"loafle.com/overflow/crawler_go/config"
"encoding/json"
"strings"
)
const (
OVERFLOW_CONFIG_PATH = "/Overflow/Config"
)
type ConfigManager struct {
idMap map[string]string
}
func (c *ConfigManager) readByTempConfig(cn *config.Config) (error) {
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
b, err := ioutil.ReadFile(pwd+"/example.json")
err = json.Unmarshal(b,&cn)
return err
}
func (c *ConfigManager) writeConfig(cn config.Config) (error){
var fileName = cn.Id
fileJson, _ := json.Marshal(cn)
path, _ := c.getFilePath(cn)
err := ioutil.WriteFile(path + "/" + fileName + ".json", fileJson, 0644)
c.idMap[cn.Id] = path + "/"
return err
}
func (c *ConfigManager) getFilePath(cn config.Config) (string, error){
var parentPath string = strings.Join(configSettingFolder,"")
cctmp := cn.Crawler.Container
cctmps := strings.Split(cctmp,"_")
containerPath := cctmps[0]
cns := strings.Split(cn.Crawler.Name, "_")
cnf := cns[0]
rs := parentPath + OVERFLOW_CONFIG_PATH +"/"+containerPath+"/"+cnf
err := checkFolder(rs)
return rs, err
}
func (c *ConfigManager) AddConfig(b []byte) (error) {
var err error
cn := config.Config{}
if len(b) == 0 || b == nil {
err = c.readByTempConfig(&cn)
} else {
err = json.Unmarshal(b, &cn)
}
if err != nil {
log.Fatal(err)
}
c.writeConfig(cn)
return err
}
func (c *ConfigManager) GetConfigById(id string) (string) {
return c.idMap[id]
}
func checkFolder(path string) (error) {
_, err := os.Stat(path)
if err != nil {
log.Println(err)
}
if os.IsNotExist(err) {
err = nil
os.MkdirAll(path, os.ModePerm)
}
return err
}
func NewConfigManager() *ConfigManager {
var c ConfigManager
c.idMap = make(map[string]string)
return &c
}
func Start(b []byte) {
// config json stream read
// config json byte read
var err error
cm := ConfigManager{}
c := config.Config{}
cm.idMap = make(map[string]string)
if len(b) == 0 || b == nil {
err = cm.readByTempConfig(&c)
} else {
err = json.Unmarshal(b, &c)
}
if err != nil {
log.Fatal(err)
}
cm.writeConfig(c)
}
// config json save folder
// create folder for config
// config json parse