content endpoint
This commit is contained in:
@@ -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
@@ -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[:])
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user