diff options
| author | Jan Wolff <janw@mailbox.org> | 2025-09-12 09:34:01 +0200 |
|---|---|---|
| committer | Jan Wolff <janw@mailbox.org> | 2025-09-12 09:34:01 +0200 |
| commit | 283c31564a9d5dab4b8b71d7498886b0cd20a999 (patch) | |
| tree | bc15867a389f25b1855042b5af20efba96c68dbb /controller/file.go | |
initial commit
Diffstat (limited to 'controller/file.go')
| -rw-r--r-- | controller/file.go | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/controller/file.go b/controller/file.go new file mode 100644 index 0000000..53121d5 --- /dev/null +++ b/controller/file.go @@ -0,0 +1,79 @@ +package controller + +import ( + "fmt" + "io" + "net/http" + "time" + + "drop.janw.name/storage" +) + +const MAX_FILESIZE = (1 << 19) * 100 + +func (app App) FilePost(res http.ResponseWriter, req *http.Request) { + if !app.requireAuth(res, req) { + return + } + + if err := req.ParseMultipartForm(MAX_FILESIZE); err != nil { + panic(err) + } + + formFile, formFileHeader, err := req.FormFile("file") + if err != nil { + panic(err) + } + + protected := req.FormValue("protect") == "on" + + fileData, err := io.ReadAll(formFile) + if err != nil { + panic(err) + } + + file := storage.File{ + Protected: protected, + Filename: formFileHeader.Filename, + Data: fileData, + AvailableUntil: time.Now().Add(time.Hour * 2), + } + + key, err := app.storage.Put(file) + if err != nil { + panic(err) + } + + app.tmpl.ExecuteTemplate(res, "uploaded", struct { + DownloadURL string + }{ + DownloadURL: fmt.Sprintf("%s/%s", app.config.Http.BaseAddress, key), + }) +} + +func (app App) FileGet(res http.ResponseWriter, req *http.Request) { + fileId := req.PathValue("file") + + file, _ := app.storage.Get(fileId) + + if file == nil || !file.IsAvailable() { + if !app.requireAuth(res, req) { + return + } + + res.WriteHeader(http.StatusNotFound) + app.tmpl.ExecuteTemplate(res, "404", nil) + return + } + + if file.Protected && !app.requireAuth(res, req) { + return + } + + res.Header().Add("Content-Type", "application/octet-stream") + res.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", file.Filename)) + + if _, err := res.Write(file.Data); err != nil { + panic(err) + } +} |
