使用通配符*引用目录中的文件

时间:2014-07-25 18:09:15

标签: go

我试图使用这个Go lang论坛软件https://github.com/kjk/fofou。它需要顶级论坛目录中的配置文件来指定有关论坛的某些信息(名称,URL等)。例如,软件设计者使用的文件是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

1 个答案:

答案 0 :(得分:3)

您不应该检查来自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"))
}

playground

//修改

从我们的讨论中,您必须使用完整路径/home/user/go/....../forums/或相对路径./forums/

相关问题