如何在golang中找到基于文件名regex的所有扩展名的电子文件



以下代码可以打开名为rx80_AWS.png的文件,但我想打开名为rx80_AWS*的文件,而不考虑扩展名,因为文件名是唯一的,但我们在文件夹中上传.png.pdf和.jpeg文件

func DownloadCert(w http.ResponseWriter, r *http.Request) {
Openfile, err := os.Open("./certificate/rx80_AWS.png") //Open the file to be downloaded later
defer Openfile.Close()                                 //Close after function return
fmt.Println("FIle:", files)
if err != nil {
http.Error(w, "File not found.", 404) //return 404 if file is not found
return
}
tempBuffer := make([]byte, 512)                       //Create a byte array to read the file later
Openfile.Read(tempBuffer)                             //Read the file into  byte
FileContentType := http.DetectContentType(tempBuffer) //Get file header
FileStat, _ := Openfile.Stat()                     //Get info from file
FileSize := strconv.FormatInt(FileStat.Size(), 10) //Get file size as a string
Filename := attuid + "_" + skill
//Set the headers
w.Header().Set("Content-Type", FileContentType+";"+Filename)
w.Header().Set("Content-Length", FileSize)
Openfile.Seek(0, 0)  //We read 512 bytes from the file already so we reset the offset back to 0
io.Copy(w, Openfile) //'Copy' the file to the client
}

使用filepath.Glob

files, err := filepath.Glob("certificate/rx80_AWS*")
if err != nil {
// handle errors
}
for _, filename in files {
//...handle each file...
}

下面是一个通过匹配/bin/*cat(匹配catzcat等(来处理操场的示例。

最新更新