func readFiles(files ...string) []byte { lfs := len(files) chContent := make(chan []byte, lfs) for _, file := range files { go func(chContent chan []byte, configPath string) { chContent <- format(configPath) }(chContent, file) } bytess := make([][]byte, 0, lfs) for i := 1; i <= lfs; i++ { content := <-chContent if len(content) != 0 { bytess = append(bytess, content) } } buf := bytes.NewBufferString(`{`) buf.Write(bytes.Join(bytess, []byte(`,`))) buf.WriteString(`}`) var contentBuf bytes.Buffer err := json.Compact(&contentBuf, buf.Bytes()) if err != nil { log.Debug("<readFiles> jsonData: ", buf.String()) log.Fatal("<readFiles> error: ", err) } return contentBuf.Bytes() }
func Dir(configDir string) *Config { configDir = filepath.Clean(configDir) fis, err := ioutil.ReadDir(configDir) if err != nil { log.Fatal("<Dir> error: ", err) } var files []string for _, fi := range fis { fileName := fi.Name() if fi.IsDir() || fileName[0] == ignoreFirst { continue } files = append(files, filepath.Join(configDir, fileName)) } conf := loadFiles(files...) mu.Lock() conf.dataType = "directory" conf.target = configDir mu.Unlock() return conf }
func format(configPath string) []byte { data, err := ioutil.ReadFile(configPath) if err != nil { log.Fatal("<format> error: ", err) } return bytes.TrimSpace(regexpNote.ReplaceAll(data, []byte(``))) }
func (c *Config) Load(configDir string) { conf := config.Dir(configDir).Load(c) configDir = conf.Target() if dataFi, err := os.Stat(configDir); err == nil { c.set(configDir, dataFi.ModTime().Unix()) c.preSet() } else { log.Fatal("<Config.Load> error:", err) } }
func (c *Config) Load(i interface{}) *Config { mu.RLock() data := c.data mu.RUnlock() err := json.Unmarshal(data, i) if err != nil { log.Debug("<Config.Load> jsonData: ", c.String()) log.Fatal("<Config.Load> error: ", err) } return c }
func Data(data string) *Config { data = `{` + data + `}` var buf bytes.Buffer err := json.Compact(&buf, []byte(data)) if err != nil { log.Debug("<Data> jsonData: ", data) log.Fatal("<Data> error: ", err) } return &Config{ dataType: "data", data: buf.Bytes(), } }
func Glob(pattern string) *Config { files, err := filepath.Glob(pattern) if err != nil { log.Fatal("<Glob> error: ", err) } conf := loadFiles(files...) mu.Lock() conf.dataType = "glob" conf.target = pattern mu.Unlock() return conf }
func (p *Page) ListenAndServe(addr string, i interface{}) { if p.Config.SupportStatic { p.handleRootStatic(p.Config.RootStaticFiles) p.handleStatic() } if p.Config.AccessHtml { p.handleStaticHtml() } p.handleRoute(i) err := http.ListenAndServe(addr, nil) if err != nil { log.Fatal("<Page.ListenAndServe> ", err) } }