process & save upload
This commit is contained in:
+75
-6
@@ -1,11 +1,17 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"log"
|
"log"
|
||||||
"mime"
|
"mime"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
@@ -23,11 +29,11 @@ func health(w http.ResponseWriter, r *http.Request) {
|
|||||||
type uploadInput struct {
|
type uploadInput struct {
|
||||||
Reader io.Reader
|
Reader io.Reader
|
||||||
Filename string
|
Filename string
|
||||||
MimeType string
|
MIMEType string
|
||||||
Type ContentType
|
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) {
|
return func(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method != http.MethodPost {
|
if r.Method != http.MethodPost {
|
||||||
http.Error(w, "invalid method", http.StatusMethodNotAllowed)
|
http.Error(w, "invalid method", http.StatusMethodNotAllowed)
|
||||||
@@ -44,6 +50,11 @@ func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
idLength := 16
|
||||||
|
if r.URL.Query().Get("idlength") == "short" {
|
||||||
|
idLength = 10
|
||||||
|
}
|
||||||
|
|
||||||
var input uploadInput
|
var input uploadInput
|
||||||
switch mediaType {
|
switch mediaType {
|
||||||
case "multipart/form-data": // file uploads
|
case "multipart/form-data": // file uploads
|
||||||
@@ -61,9 +72,9 @@ func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
input.MimeType, err = detectMimeType(file)
|
input.MIMEType, err = detectMimeType(file)
|
||||||
if err != nil {
|
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)
|
http.Error(w, "failed to detect mime type", http.StatusInternalServerError)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -74,14 +85,72 @@ func upload(db *gorm.DB, cfg Config) http.HandlerFunc {
|
|||||||
input = uploadInput{
|
input = uploadInput{
|
||||||
Reader: r.Body,
|
Reader: r.Body,
|
||||||
Filename: "paste.txt",
|
Filename: "paste.txt",
|
||||||
MimeType: "text/plain; charset=utf-8",
|
MIMEType: "text/plain; charset=utf-8",
|
||||||
Type: ContentPaste,
|
Type: ContentPaste,
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType)
|
http.Error(w, "unsupported Content-Type", http.StatusUnsupportedMediaType)
|
||||||
return
|
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)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ func main() {
|
|||||||
|
|
||||||
log.Println("config loaded")
|
log.Println("config loaded")
|
||||||
|
|
||||||
_, err = initDatabase(config.DatabasePath)
|
db, err := initDatabase(config.DatabasePath)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
@@ -27,7 +27,7 @@ func main() {
|
|||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pages, err := template.ParseFiles("templates/home.html", "templates/paste.html")
|
pages, err := template.ParseFiles("templates/home.html")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -45,6 +45,7 @@ func main() {
|
|||||||
log.Println("render home page:", err)
|
log.Println("render home page:", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
mux.HandleFunc("POST /upload", uploadHandler(db, config))
|
||||||
mux.HandleFunc("GET /health", health)
|
mux.HandleFunc("GET /health", health)
|
||||||
|
|
||||||
log.Println("listening on http://localhost:8080")
|
log.Println("listening on http://localhost:8080")
|
||||||
|
|||||||
Reference in New Issue
Block a user