[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=[]

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章