process & save upload

This commit is contained in:
2026-11-08 21:18:53 -05:00
parent 1c99c5dd11
commit 673c039d1c
2 changed files with 78 additions and 8 deletions
+75 -6
View File
@@ -1,11 +1,17 @@
package main
import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"log"
"mime"
"net/http"
"os"
"path/filepath"
"time"
"unicode/utf8"
"gorm.io/gorm"
)
@@ -23,11 +29,11 @@ func health(w http.ResponseWriter, r *http.Request) {
type uploadInput struct {
Reader io.Reader
Filename string
MimeType string
MIMEType string
Type ContentType
}
func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
func uploadHandler(db *gorm.DB, cfg Config) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "invalid method", http.StatusMethodNotAllowed)
@@ -44,6 +50,11 @@ func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
return
}
idLength := 16
if r.URL.Query().Get("idlength") == "short" {
idLength = 10
}
var input uploadInput
switch mediaType {
case "multipart/form-data": // file uploads
@@ -61,9 +72,9 @@ func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
return
}
input.MimeType, err = detectMimeType(file)
input.MIMEType, err = detectMimeType(file)
if err != nil {
log.Printf("detect file mime type: %v", err)
log.Println("detect file mime type:", err)
http.Error(w, "failed to detect mime type", http.StatusInternalServerError)
return
}
@@ -74,14 +85,72 @@ func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
input = uploadInput{
Reader: r.Body,
Filename: "paste.txt",
MimeType: "text/plain; charset=utf-8",
MIMEType: "text/plain; charset=utf-8",
Type: ContentPaste,
}
default:
http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType)
return
}
// todo: generate id -> derive storage path -> hash + save to disk -> insert to database
// todo: clean up after failure, maybe defer a function before any of this, that checks if everything passed?
id := generateId(idLength)
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)
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)
return
}
hasher := sha256.New()
size, err := io.Copy(io.MultiWriter(dest, hasher), input.Reader)
if err != nil {
log.Println("write file:", err)
http.Error(w, "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)
}
createdAt := time.Now().UTC().Unix()
if utf8.RuneCountInString(input.Filename) > 255 {
name := []rune(input.Filename)
ext := []rune(filepath.Ext(input.Filename))
if len(ext) >= 255 {
ext = nil
}
input.Filename = string(name[:255-len(ext)]) + string(ext)
}
upload := Upload{
ID: id,
Type: input.Type,
Filename: input.Filename,
MIMEType: input.MIMEType,
Size: size,
SHA256: hasher.Sum(nil),
CreatedAt: createdAt,
LastAccessedAt: createdAt,
}
err = insertUpload(db, &upload)
if err != nil {
log.Println("save upload:", err)
http.Error(w, "failed to save upload", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(upload); err != nil {
log.Println("failed to encode response:", err)
}
}
}
+3 -2
View File
@@ -15,7 +15,7 @@ func main() {
log.Println("config loaded")
_, err = initDatabase(config.DatabasePath)
db, err := initDatabase(config.DatabasePath)
if err != nil {
log.Fatal(err)
@@ -27,7 +27,7 @@ func main() {
log.Fatal(err)
}
pages, err := template.ParseFiles("templates/home.html", "templates/paste.html")
pages, err := template.ParseFiles("templates/home.html")
if err != nil {
log.Fatal(err)
}
@@ -45,6 +45,7 @@ func main() {
log.Println("render home page:", err)
}
})
mux.HandleFunc("POST /upload", uploadHandler(db, config))
mux.HandleFunc("GET /health", health)
log.Println("listening on http://localhost:8080")