config_manager_go/config.go
2017-04-13 19:51:48 +09:00

98 lines
1.6 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 {
}
func (config *ConfigManager) readByTempConfig(c *config.Config) (error) {
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
b, err := ioutil.ReadFile(pwd+"/example.json")
err = json.Unmarshal(b,&c)
return err
}
func (config *ConfigManager) writeConfig(c config.Config) (error){
var fileName = c.Id
fileJson, _ := json.Marshal(c)
path, _ := config.getFilePath(c)
err := ioutil.WriteFile(path + "/" + fileName + ".json", fileJson, 0644)
return err
}
func (config *ConfigManager) getFilePath(c config.Config) (string, error){
var parentPath string = strings.Join(configSettingFolder,"")
cctmp := c.Crawler.Container
cctmps := strings.Split(cctmp,"_")
containerPath := cctmps[0]
cns := strings.Split(c.Crawler.Name, "_")
cn := cns[0]
rs := parentPath + OVERFLOW_CONFIG_PATH +"/"+containerPath+"/"+cn
err := checkFolder(rs)
return rs, err
}
func checkFolder(path string) (error) {
_, err := os.Stat(path)
if err != nil {
log.Println(err)
}
if os.IsNotExist(err) {
os.MkdirAll(path, os.ModePerm)
}
return nil
}
func Start(b []byte) {
// config json stream read
// config json byte read
var err error
cm := ConfigManager{}
c := config.Config{}
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