content endpoint

This commit is contained in:
2026-11-10 13:37:46 -05:00
parent 77e28c42d2
commit 4751899357
4 changed files with 56 additions and 1 deletions
+46
View File
@@ -214,6 +214,52 @@ func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
}
}
func contentHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if !validPasteId(id) {
http.NotFound(w, r)
return
}
path := getStoragePath(cfg.UploadDir, id)
upload, err := getUploadById(db.WithContext(r.Context()), id)
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
http.NotFound(w, r)
return
}
log.Println("get upload:", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
now := time.Now().UTC().Unix()
if upload.ExpiresAt != nil && now >= *upload.ExpiresAt {
http.NotFound(w, r)
return
}
file, err := os.Open(path)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
http.NotFound(w, r)
return
}
log.Println("get upload file:", err)
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
defer file.Close()
w.Header().Set("Content-Type", upload.MIMEType)
w.Header().Set("X-Content-Type-Options", "nosniff")
http.ServeContent(w, r, upload.Filename, time.Unix(upload.CreatedAt, 0), file)
}
}
func detectMimeType(file io.ReadSeeker) (string, error) {
var buffer [512]byte
n, readErr := io.ReadFull(file, buffer[:])