How to find thee files with all extension based on file name regex in golang

1.2k views Asked by At

Below code can open file with name rx80_AWS.png but I want to open file with rx80_AWS* irrespective of the extension as the file names will be unique but we upload .png .pdf and .jpeg files in thee folder

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

}
1

There are 1 answers

2
erik258 On BEST ANSWER

Use filepath.Glob.

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

Here is an example that works with the playground by matching /bin/*cat (matching cat, zcat, etc).