From d00280d5497d7dd67eeca48becb6c0a2dcb94fd7 Mon Sep 17 00:00:00 2001 From: Alexandru Date: Wed, 18 Sep 2024 22:11:43 +0300 Subject: [PATCH] do this shit --- .gitignore | 2 +- go.mod | 3 +++ server.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 go.mod create mode 100644 server.go diff --git a/.gitignore b/.gitignore index adf8f72..40ec471 100644 --- a/.gitignore +++ b/.gitignore @@ -20,4 +20,4 @@ # Go workspace file go.work - +files/ diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..465f9e7 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module fzorb.xyz/filehandler + +go 1.23.1 diff --git a/server.go b/server.go new file mode 100644 index 0000000..7fd1679 --- /dev/null +++ b/server.go @@ -0,0 +1,54 @@ +package main + +import ( + "fmt" + "io" + "math/rand" + "net/http" + "os" + "path/filepath" +) + +func uploadFile(wr http.ResponseWriter, rq *http.Request) { + fmt.Println("File Upload Endpoint Hit") + err := rq.ParseMultipartForm(128 << 20) + if err != nil { + http.Error(wr, "Unable to parse form", http.StatusBadRequest) + return + } + + // Retrieve the uploaded file using the form field `myFile` + file, handler, er := rq.FormFile("file") + if er != nil { + http.Error(wr, "Error getting the file", http.StatusBadRequest) + return + } + if handler.Size > 128<<20 { + http.Error(wr, "Max file size is 128mb.", http.StatusRequestEntityTooLarge) + return + } + defer file.Close() + + fname := fmt.Sprintf("%d%s", rand.Intn(1000000), filepath.Ext(handler.Filename)) + destPath := filepath.Join("./files", fname) + destFile, er := os.Create(destPath) + if er != nil { + http.Error(wr, "OOPSIE WOOPSIE!! Uwu We made a fucky wucky!! A wittle fucko boingo! The code monkeys at our headquarters are working VEWY HAWD to fix this!", http.StatusInternalServerError) + return + } + defer destFile.Close() + _, er = io.Copy(destFile, file) + if er != nil { + http.Error(wr, "OOPSIE WOOPSIE!! Uwu We made a fucky wucky!! A wittle fucko boingo! The code monkeys at our headquarters are working VEWY HAWD to fix this!", http.StatusInternalServerError) + return + } + + fmt.Fprintf(wr, "Success! Your file should now be accessible here: https://files.fzorb.xyz/%s\n", fname) + fmt.Printf("File successfully saved to: %s\n", destPath) +} + +func main() { + fmt.Println("Server now listening on port 48723") + http.HandleFunc("/upload", uploadFile) + http.ListenAndServe(":48723", nil) +}