Golang 在 filepath.Glob 裡使用含方括號([ 跟 ])的路徑
由於 Golang 語言限制,filepath.Glob 裡面有一些字元是不能用的,例如說 [ 跟 ] 就是其中之一(還有 * 號,但是大部分作業系統都不會讓你把 * 號當作資料夾名稱,所以在這裡就不作處理了。一般來說,如果你要打開一個包含 [ ] 的路徑, filepath.Glob 會回傳空值。 path := "mymusic[mp3]/*" files, err := filepath.Glob(path); // files 會回傳空值 所以,很多工程師就幹脆不在資料夾名稱裡面使用 [ 跟 ],但是作為開發網頁版的檔案管理器,由於作為工程師是無法預計用戶的使用方式,我們必將要在 Glob 裡面支援 [ 跟 ],而方法可能比你想像中的簡單: realpath := "mymusic[mp3]" files, _ := filepath.Glob(realpath + "*") //這裡的 files 會是空值,寫在這裡是為了在下面省下一個 else 的 case if (strings.Contains(realpath, "[") == true || strings.Contains(realpath, "]") == true){ if (len(files) == 0){ //特別處理模式,以 * 號取代 [ 跟 ] newSearchPath := strings.ReplaceAll(realpath, "[","*") newSearchPath = strings.ReplaceAll(newSearchPath, "]","*") //掃描與輸入路徑相近的路徑名稱 tmpFilelist, _ := filepath.Glob(newSearchPath + "*") //在每個相近路徑中,找出擁有正確路徑的檔案 for _, file := range tmpFilelist{ file = filepath.ToSlash(file) if strings.Contains(file, realpath){ files = append(files, file) } } } } //正確回傳 log.Println(files)
PHP7 下檔案名稱太長導致 glob 回傳 false 的問題
很多時候在開發 PHP 的時候我們都會使用這個超級方便的 glob(*) 功能。簡單來說就是把一個資料夾或路徑內的檔案以 array 方式回傳的方法。然而,在最近的 ArOZ Online 測試伺服器更新之後發現了 File Explorer 在開啟某些資料夾時出現 PHP ERROR 的問題。後來經過一堆檢測之後發現原來是檔案名稱太長了,結果 glob 就直接回傳 false 。 原本的 listdir.php //Some code here for auth and var parsing if (file_exists($path) && is_dir($path)){ $filelist = glob($path . "/*"); //Other code } 要解決這個問題,我們需要把它改成使用 scandir ,然而由於 scandir 會多了很多代碼,為了節省處理能力,我們只在需要的時候使用 scandir 就好。結果新的 glob 部分就變成了這樣: //Some code here for auth and var parsing if (file_exists($path) && is_dir($path)){ $filelist = glob($path . "/*"); if ($filelist === false){ //Something went wrong while trying to list the directory using glob. Try scandir $scanResults = scandir($path); $filelist = []; $useAbnormalFilter = true; foreach ($scanResults as $fileObj){ if ($fileObj != "." && $fileObj != ".."){ array_push($filelist, $path . "/" . $fileObj); } } } //Other code } 就是這樣,File Explorer 的顯示就回復正常了。對,這都是 Windows 的錯。