50 lines
		
	
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
		
		
			
		
	
	
			50 lines
		
	
	
	
		
			1.2 KiB
		
	
	
	
		
			Go
		
	
	
	
	
	
|  | package web | ||
|  | 
 | ||
|  | import ( | ||
|  | 	"database/sql" | ||
|  | 	"io" | ||
|  | 	"net/http" | ||
|  | 	"strconv" | ||
|  | 
 | ||
|  | 	"codeberg.org/u1f320/filer/db/queries" | ||
|  | 	"emperror.dev/errors" | ||
|  | 	"github.com/go-chi/chi/v5" | ||
|  | 	"github.com/rs/zerolog/log" | ||
|  | ) | ||
|  | 
 | ||
|  | func (app *App) showFile(w http.ResponseWriter, r *http.Request) { | ||
|  | 	ctx := r.Context() | ||
|  | 	hash := chi.URLParam(r, "hash") | ||
|  | 	filename := chi.URLParam(r, "filename") | ||
|  | 
 | ||
|  | 	file, err := app.db.GetFileByName(ctx, queries.GetFileByNameParams{ | ||
|  | 		Filename: filename, | ||
|  | 		Hash:     hash, | ||
|  | 	}) | ||
|  | 	if err != nil { | ||
|  | 		if errors.Is(err, sql.ErrNoRows) { | ||
|  | 			http.Error(w, "File not found", http.StatusNotFound) | ||
|  | 			return | ||
|  | 		} | ||
|  | 
 | ||
|  | 		log.Err(err).Str("hash", hash).Str("name", filename).Msg("getting file from database") | ||
|  | 		http.Error(w, "Internal server error", http.StatusInternalServerError) | ||
|  | 		return | ||
|  | 	} | ||
|  | 
 | ||
|  | 	data, err := app.db.Store.GetFile(file.ID) | ||
|  | 	if err != nil { | ||
|  | 		log.Err(err).Str("hash", hash).Str("name", filename).Msg("getting file data") | ||
|  | 		http.Error(w, "Internal server error", http.StatusInternalServerError) | ||
|  | 		return | ||
|  | 	} | ||
|  | 
 | ||
|  | 	w.Header().Add("Content-Type", file.ContentType) | ||
|  | 	w.Header().Add("Content-Length", strconv.FormatInt(file.Size, 10)) | ||
|  | 	_, err = io.Copy(w, data) | ||
|  | 	if err != nil { | ||
|  | 		log.Err(err).Str("hash", hash).Str("name", filename).Msg("writing file data") | ||
|  | 		return | ||
|  | 	} | ||
|  | } |