-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(handlers): add download endpoint for unsupported file types
- Added the /download endpoint to force file download. - Implemented a handler that validates the path and searches for the corresponding file in the "uploads" directory. - For unsupported files, an HTML page is displayed with a download link. - Improved validation of directories and files, with proper error handling. - Files are now served with the "Content-Disposition: attachment" header to force download.
- Loading branch information
1 parent
b3edf4b
commit 44c00fe
Showing
4 changed files
with
171 additions
and
46 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
package handlers | ||
|
||
import ( | ||
"fmt" | ||
"net/http" | ||
"os" | ||
"path/filepath" | ||
) | ||
|
||
func DownloadHandler(w http.ResponseWriter, r *http.Request) { | ||
path := r.URL.Path[len("/download/"):] | ||
if path == "" { | ||
http.NotFound(w, r) | ||
return | ||
} | ||
|
||
dirPath := filepath.Join("uploads", path) | ||
|
||
dirInfo, err := os.Stat(dirPath) | ||
if os.IsNotExist(err) || !dirInfo.IsDir() { | ||
http.NotFound(w, r) | ||
return | ||
} | ||
|
||
files, err := os.ReadDir(dirPath) | ||
if err != nil || len(files) == 0 { | ||
http.NotFound(w, r) | ||
return | ||
} | ||
|
||
fileInfo, err := files[0].Info() | ||
if err != nil || !fileInfo.Mode().IsRegular() { | ||
http.NotFound(w, r) | ||
return | ||
} | ||
|
||
filePath := filepath.Join(dirPath, fileInfo.Name()) | ||
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileInfo.Name())) | ||
w.Header().Set("Content-Type", "application/octet-stream") | ||
http.ServeFile(w, r, filePath) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters