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
+8
View File
@@ -57,3 +57,11 @@ func initDatabase(path string) (*gorm.DB, error) {
func insertUpload(db *gorm.DB, upload *Upload) error {
return db.Create(upload).Error
}
func getUploadById(db *gorm.DB, id string) (*Upload, error) {
var upload Upload
if err := db.First(&upload, "id = ?", id).Error; err != nil {
return nil, err
}
return &upload, nil
}
+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[:])
+1
View File
@@ -45,6 +45,7 @@ func main() {
log.Println("render home page:", err)
}
})
mux.HandleFunc("GET /{id}", contentHandler(db, config))
mux.HandleFunc("POST /upload", uploadHandler(db, config))
mux.HandleFunc("GET /health", health)
+1 -1
View File
@@ -16,7 +16,7 @@ goals:
# roadmap/todo
- [x] upload endpoint
- [ ] content endpoints
- [x] content endpoint
- [ ] update last accessed at
- use a memory cache and batch commit to database to keep performance
- [ ] paste page