diff --git a/database.go b/database.go index 62d02d2..2bae5fc 100644 --- a/database.go +++ b/database.go @@ -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 +} diff --git a/handlers.go b/handlers.go index 5d0a23c..363f3da 100644 --- a/handlers.go +++ b/handlers.go @@ -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[:]) diff --git a/main.go b/main.go index 572f472..08012c8 100644 --- a/main.go +++ b/main.go @@ -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) diff --git a/readme.md b/readme.md index 45e4fab..a4de147 100644 --- a/readme.md +++ b/readme.md @@ -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