我正在尝试使用这个 Go 语言论坛软件 https://github.com/kjk/fofou .它需要顶级论坛目录中的配置文件来指定有关论坛的某些信息(名称、网址等)。例如,软件设计师使用的文件是 forums/sumatrapdf_config.json
在main.go中有读取论坛配置文件的函数
func readForumConfigs(configDir string) error {
pat := filepath.Join(configDir, "*_config.json")
fmt.Println("path", pat)
files, err := filepath.Glob(pat)
fmt.Println("files", files, err)
if err != nil {
return err
}
if files == nil {
return errors.New("No forums configured!")
}
for _, configFile := range files {
var forum ForumConfig
b, err := ioutil.ReadFile(configFile)
if err != nil {
return err
}
err = json.Unmarshal(b, &forum)
if err != nil {
return err
}
if !forum.Disabled {
forums = append(forums, &forum)
}
}
if len(forums) == 0 {
return errors.New("All forums are disabled!")
}
return nil
}
我试过 Join 的第二个参数,具体通过文件名和通配符 * 调用它,但我不断收到错误消息,告诉我没有文件。
the log statements show the path that it's checking as well as the fact that no files are found
path forums/*funnyforum_config.json files [] 2014/07/25 10:34:11 Failed to read forum configs, err: No forums configured!
如果我尝试用通配符 *
描述配置,就会发生同样的事情,就像软件创建者在源代码中所做的那样
func readForumConfigs(configDir string) error { pat := filepath.Join(configDir, "*_config.json") fmt.Println("path", pat) files, err := filepath.Glob(pat) fmt.Println("files", files)
path forums/*_config.json files [] 2014/07/25 10:40:38 Failed to read forum configs, err: No forums configured!
在论坛目录下,我放了各种配置文件
funnyforum_config.json _config.json
以及它附带的配置
sumatrapdf_config.json
最佳答案
你不是在检查 glob
的错误,你应该,你也可以用不同的方式实现它:
func FilterDirs(dir, suffix string) ([]string, error) {
files, err := ioutil.ReadDir(dir)
if err != nil {
return nil, err
}
res := []string{}
for _, f := range files {
if !f.IsDir() && strings.HasSuffix(f.Name(), suffix) {
res = append(res, filepath.Join(dir, f.Name()))
}
}
return res, nil
}
func FilterDirsGlob(dir, suffix string) ([]string, error) {
return filepath.Glob(filepath.Join(dir, suffix))
}
func main() {
fmt.Println(FilterDirs("/tmp", ".json"))
fmt.Println(FilterDirsGlob("/tmp", "*.json"))
}
//编辑
根据我们的讨论,您必须使用完整路径 /home/user/go/....../forums/
或相对路径 ./forums/
.
关于go - 使用通配符 * 引用目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24961974/