33 lines
665 B
Go
33 lines
665 B
Go
package handlers
|
|
|
|
import (
|
|
"fmt"
|
|
"net/http"
|
|
"path/filepath"
|
|
"strconv"
|
|
"threadr/models"
|
|
)
|
|
|
|
func FileHandler(app *App) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
fileIDStr := r.URL.Query().Get("id")
|
|
fileID, err := strconv.ParseInt(fileIDStr, 10, 64)
|
|
if err != nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
file, err := models.GetFileByID(app.DB, fileID)
|
|
if err != nil || file == nil {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
|
|
fileExt := filepath.Ext(file.OriginalName)
|
|
fileName := fmt.Sprintf("%d%s", fileID, fileExt)
|
|
filePath := filepath.Join(app.Config.FileStorageDir, fileName)
|
|
|
|
http.ServeFile(w, r, filePath)
|
|
}
|
|
}
|