From 123e47596be84e534b271e72a1a2bd5240d6cf23 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Fri, 20 Nov 2026 21:57:06 -0500 Subject: [PATCH] page on failure --- handlers.go | 84 ++++++++++++++++++++++----------------------- pages.go | 13 +++++++ readme.md | 4 +-- routes.go | 8 ++--- static/css/main.css | 1 + 5 files changed, 62 insertions(+), 48 deletions(-) diff --git a/handlers.go b/handlers.go index 7e5890b..d9ec7c4 100644 --- a/handlers.go +++ b/handlers.go @@ -52,7 +52,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost && r.Method != http.MethodPut { w.Header().Set("Allow", "POST,PUT") - http.Error(w, "invalid method", http.StatusMethodNotAllowed) + pages.HTTPError(w, r, "invalid method", http.StatusMethodNotAllowed) return } @@ -64,7 +64,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { if r.Method == http.MethodPost || r.Header.Get("Content-Type") != "" { mediaType, _, err = mime.ParseMediaType(r.Header.Get("Content-Type")) if err != nil { - http.Error(w, "failed to find or parse Content-Type", http.StatusBadRequest) + pages.HTTPError(w, r, "failed to find or parse Content-Type", http.StatusBadRequest) return } } @@ -84,11 +84,11 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { } if err != nil { if _, ok := errors.AsType[*http.MaxBytesError](err); ok { - http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) + pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) return } - http.Error(w, "invalid file", http.StatusBadRequest) + pages.HTTPError(w, r, "invalid file", http.StatusBadRequest) return } defer file.Close() @@ -96,11 +96,11 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { input.MIMEType, err = detectMimeType(file) if err != nil { log.Println("detect file mime type:", err) - http.Error(w, "failed to detect mime type", http.StatusInternalServerError) + pages.HTTPError(w, r, "failed to detect mime type", http.StatusInternalServerError) return } if slices.Contains(cfg.BannedMIMETypes, input.MIMEType) { - http.Error(w, "content type not allowed", http.StatusBadRequest) + pages.HTTPError(w, r, "content type not allowed", http.StatusBadRequest) return } input.Reader = file @@ -110,7 +110,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { r.Body = http.MaxBytesReader(w, r.Body, cfg.MaxPasteBytes) var content string if mediaType == "application/x-www-form-urlencoded" { - err := r.ParseForm() + err = r.ParseForm() if err == nil { content = r.PostForm.Get("content") } @@ -124,16 +124,16 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { if err != nil { if _, ok := errors.AsType[*http.MaxBytesError](err); ok { - http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) + pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) return } - http.Error(w, "invalid paste upload", http.StatusBadRequest) + pages.HTTPError(w, r, "invalid paste upload", http.StatusBadRequest) return } if strings.TrimSpace(content) == "" { - http.Error(w, "paste cannot be empty", http.StatusBadRequest) + pages.HTTPError(w, r, "paste cannot be empty", http.StatusBadRequest) return } @@ -144,7 +144,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { Type: ContentPaste, } default: - http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType) + pages.HTTPError(w, r, "unsupported Content-Type", http.StatusUnsupportedMediaType) return } @@ -158,7 +158,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { selected, found := findExpiry(cfg.Expiries, expLabel) if !found { - http.Error(w, "invalid expiry", http.StatusBadRequest) + pages.HTTPError(w, r, "invalid expiry", http.StatusBadRequest) return } @@ -174,14 +174,14 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { path := getStoragePath(cfg.UploadDir, id) if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { log.Println("create directories:", err) - http.Error(w, "failed to save upload", http.StatusInternalServerError) + pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) return } dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) if err != nil { log.Println("create file:", err) - http.Error(w, "faield to save upload", http.StatusInternalServerError) + pages.HTTPError(w, r, "faield to save upload", http.StatusInternalServerError) return } @@ -199,23 +199,23 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader) if err != nil { if _, ok := errors.AsType[*http.MaxBytesError](err); ok { - http.Error(w, "upload too large", http.StatusRequestEntityTooLarge) + pages.HTTPError(w, r, "upload too large", http.StatusRequestEntityTooLarge) return } log.Println("write file:", err) - http.Error(w, "faield to write upload", http.StatusInternalServerError) + pages.HTTPError(w, r, "faield to write upload", http.StatusInternalServerError) return } if err := dest.Close(); err != nil { log.Println("close file:", err) - http.Error(w, "failed to save upload", http.StatusInternalServerError) + pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) return } createdAt := time.Now().UTC().Unix() expires, err := selected.ExpiresFrom(time.Now().UTC()) if err != nil { log.Println("calc expiry:", err) // im just using slang - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } @@ -250,7 +250,7 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { err = insertUpload(db, &upload) if err != nil { log.Println("save upload:", err) - http.Error(w, "failed to save upload", http.StatusInternalServerError) + pages.HTTPError(w, r, "failed to save upload", http.StatusInternalServerError) return } saved = true @@ -280,12 +280,12 @@ func uploadHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { } } -func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.HandlerFunc { +func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker, pages *Pages) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut if !validPasteId(id) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } @@ -293,28 +293,28 @@ func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.Handle upload, err := getUploadById(db.WithContext(r.Context()), id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } log.Println("get upload:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } now := time.Now().UTC().Unix() if upload.ExpiresAt != nil && now >= *upload.ExpiresAt { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } file, err := os.Open(path) if err != nil { if errors.Is(err, os.ErrNotExist) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } log.Println("get upload file:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } @@ -346,23 +346,23 @@ func contentHandler(db *gorm.DB, cfg Config, tracker *AccessTracker) http.Handle } } -func contentInfoHandler(db *gorm.DB, tracker *AccessTracker) http.HandlerFunc { +func contentInfoHandler(db *gorm.DB, tracker *AccessTracker, pages *Pages) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id, _, _ := strings.Cut(r.PathValue("id"), ".") // remove any extension via strings.Cut if !validPasteId(id) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } upload, err := getUploadById(db, id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } log.Println("get upload:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } @@ -378,11 +378,11 @@ func contentInfoHandler(db *gorm.DB, tracker *AccessTracker) http.HandlerFunc { } } -func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { +func deleteHandler(db *gorm.DB, cfg Config, pages *Pages) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") if !validPasteId(id) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } redirect := r.URL.Query().Get("redirect") == "true" @@ -395,7 +395,7 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { var found bool scheme, token, found = strings.Cut(bearer, " ") if !found || scheme != "Bearer" { - http.Error(w, "invalid token", http.StatusBadRequest) + pages.HTTPError(w, r, "invalid token", http.StatusBadRequest) return } case http.MethodPost: @@ -406,33 +406,33 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { upload, err := getUploadById(db.WithContext(r.Context()), id) if err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } log.Println("get upload:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } if token == "" || subtle.ConstantTimeCompare([]byte(upload.DeleteToken), []byte(token)) != 1 { - http.Error(w, "invalid token", http.StatusBadRequest) + pages.HTTPError(w, r, "invalid token", http.StatusBadRequest) return } // continue to delete from database IF the file doesnt exist on disk if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) { log.Println("remove upload file:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } if err := db.WithContext(r.Context()).Delete(upload).Error; err != nil { if errors.Is(err, gorm.ErrRecordNotFound) { - http.NotFound(w, r) + pages.HTTPError(w, r, "upload not found", 404) return } log.Println("remove upload file:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } @@ -448,7 +448,7 @@ func deleteHandler(db *gorm.DB, cfg Config) http.HandlerFunc { func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *ChallengeStore) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { - http.Error(w, "Invalid form data", http.StatusBadRequest) + pages.HTTPError(w, r, "Invalid form data", http.StatusBadRequest) return } @@ -485,7 +485,7 @@ func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *Challeng return } if err != nil && clientError { - http.Error(w, err.Error(), http.StatusBadRequest) + pages.HTTPError(w, r, err.Error(), http.StatusBadRequest) return } @@ -503,7 +503,7 @@ func reportUploadHandler(db *gorm.DB, cfg Config, pages *Pages, cStore *Challeng } log.Println("failed to insert report:", err) - http.Error(w, "internal server error", http.StatusInternalServerError) + pages.HTTPError(w, r, "internal server error", http.StatusInternalServerError) return } diff --git a/pages.go b/pages.go index 00a99a6..b3152e8 100644 --- a/pages.go +++ b/pages.go @@ -152,3 +152,16 @@ func reportPageHandler(pages *Pages, store *ChallengeStore, cfg Config) http.Han }) } } + +func (pages *Pages) HTTPError(w http.ResponseWriter, r *http.Request, message string, status int) { + if strings.Contains(r.Header.Get("Accept"), "text/html") { + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.WriteHeader(status) + _ = pages.Templates.ExecuteTemplate(w, "result.html", map[string]any{ + "Title": status, + "Message": message, + }) + return + } + http.Error(w, message, status) +} diff --git a/readme.md b/readme.md index 2cd110f..daf7335 100644 --- a/readme.md +++ b/readme.md @@ -26,8 +26,8 @@ goals: - [ ] size based expiry - exclusions if below a certain size (like 5mb) - [x] delete content endpoints -- [ ] return a page for nojs clients, such as on delete or upload - - need to return one on failures as well 💔💔💔 +- [x] return a page for nojs clients, such as on delete or upload + - [x] need to return one on failures as well 💔💔💔 - [ ] max total storage usage - [x] normalize mime types (like html) - converts specific mime types to text/plain to prevent rendering diff --git a/routes.go b/routes.go index e1a51f1..63fd410 100644 --- a/routes.go +++ b/routes.go @@ -23,13 +23,13 @@ func newRouter(db *gorm.DB, cfg Config, pages *Pages, tracker *AccessTracker, cS mux.HandleFunc("GET /report", reportPageHandler(pages, cStore, cfg)) mux.HandleFunc("POST /report", reportUploadHandler(db, cfg, pages, cStore)) uploads := http.NewServeMux() - uploads.HandleFunc("GET /{id}", contentHandler(db, cfg, tracker)) - uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker)) + uploads.HandleFunc("GET /{id}", contentHandler(db, cfg, tracker, pages)) + uploads.HandleFunc("GET /{id}/info", contentInfoHandler(db, tracker, pages)) mux.Handle("/", uploads) mux.HandleFunc("POST /upload", uploadHandler(db, cfg, pages)) mux.HandleFunc("PUT /upload", uploadHandler(db, cfg, pages)) - mux.HandleFunc("DELETE /{id}", deleteHandler(db, cfg)) - mux.HandleFunc("POST /{id}/delete", deleteHandler(db, cfg)) + mux.HandleFunc("DELETE /{id}", deleteHandler(db, cfg, pages)) + mux.HandleFunc("POST /{id}/delete", deleteHandler(db, cfg, pages)) mux.HandleFunc("GET /health", health) return mux } diff --git a/static/css/main.css b/static/css/main.css index 649b340..93b77c9 100644 --- a/static/css/main.css +++ b/static/css/main.css @@ -218,6 +218,7 @@ img, video, audio { max-width: 100%; + max-height: 80dvh; } .upload-links {