[golang]filepath.Glob的缺陷,不支持多级目录

  最近在使用Gin框架的模板加载过程中,发现其对于多级子目录中的模板支持有问题(仅仅支持一级子目录),后经过查看其源码发现是filepath包的Glob方法的问题。下面先说结论:

  1. 多级目录支持有问题
  2. 不支持shell下的Glob的扩展特性

  下面是我的模板目录结构:

views
│  401.html
│  home.tmpl
│
├─admin
│  ├─authorize
│  │      index.tmpl
│  │
│  └─dicts
│          index.tmpl
│
├─signin
│      signin.html
│      signout.html
│
└─users
        index.html
View Code

  按照其他语言中Glob的使用经验,应该可以轻松的列出views目录中的.tmpl文件,于是我尝试下面的模式,结果竟然为空

filepath.Glob("./views/**/*.tmpl")

  下面是测试各种模式组合的代码:

 func testGlob(){  
  patternList := []string{
        "./views/*",
        "./views/**", /** 和一个星号一样,列出直接子目录和文件 */
        "./views/*.tmpl",
        "./views/**/*.tmpl",
        "./views/**/*",
        "./views/**/*/*.tmpl",
        "./views/*/*/*.tmpl",
        "./views/**/**/*.tmpl",
        "./views/{*.tmpl,**/*.tmpl,**/**/*.tmpl}",
    }
    for _, pattern = range patternList {
        files, err := filepath.Glob(pattern)
        if err != nil {
            slog.Error(fmt.Sprintf("filepath.Glob(\"%s\") error", pattern), err)
        }
        fmt.Printf("filepath.Glob(\"%s\") result files=[%s]\n", pattern, strings.Join(files, ";"))
    }
}

  运行结果如下:

filepath.Glob("./views/*") result files=[views\401.html;views\admin;views\home.tmpl;views\signin;views\users]
filepath.Glob("./views/**") result files=[views\401.html;views\admin;views\home.tmpl;views\signin;views\users]
filepath.Glob("./views/*.tmpl") result files=[views\home.tmpl]
filepath.Glob("./views/**/*.tmpl") result files=[]
filepath.Glob("./views/**/*") result files=[views\admin\authorize;views\admin\dicts;views\signin\signin.html;views\signin\signout.html;views\users\index.html]

filepath.Glob("./views/**/*/*.tmpl") result files=[views\admin\authorize\index.tmpl;views\admin\dicts\index.tmpl]
filepath.Glob("./views/*/*/*.tmpl") result files=[views\admin\authorize\index.tmpl;views\admin\dicts\index.tmpl]
filepath.Glob("./views/**/**/*.tmpl") result files=[views\admin\authorize\index.tmpl;views\admin\dicts\index.tmpl]
filepath.Glob("./views/{*.tmpl,**/*.tmpl,**/**/*.tmpl}") result files=[]

 

posted @ 2023-02-02 20:05  柒零壹  阅读(355)  评论(0编辑  收藏  举报