summaryrefslogtreecommitdiff
path: root/upload.go
diff options
context:
space:
mode:
Diffstat (limited to 'upload.go')
-rw-r--r--upload.go46
1 files changed, 46 insertions, 0 deletions
diff --git a/upload.go b/upload.go
new file mode 100644
index 0000000..719e519
--- /dev/null
+++ b/upload.go
@@ -0,0 +1,46 @@
+package main
+
+import (
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+
+ "github.com/google/uuid"
+)
+
+func uploadHandler(w http.ResponseWriter, r *http.Request) {
+ uid := uuid.New().String()
+ section := string(uid[len(uid)-1])
+ if err := os.MkdirAll(filepath.Join(path, section), 0777); err != nil {
+ log.Println(err)
+ http.Error(w, "can't create storage dir", http.StatusInternalServerError)
+ return
+ }
+ fp, err := os.Create(filepath.Join(path, section, uid))
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "can't create storage file", http.StatusInternalServerError)
+ return
+ }
+ defer fp.Close()
+ if _, err := io.Copy(fp, r.Body); err != nil {
+ log.Println(err)
+ http.Error(w, "can't upload storage file", http.StatusInternalServerError)
+ return
+ }
+ h := w.Header()
+ h.Set("Content-Type", "text/plain; charset=utf-8")
+ h.Set("X-Content-Type-Options", "nosniff")
+ w.WriteHeader(http.StatusCreated)
+ u, err := url.JoinPath(host, section, uid)
+ if err != nil {
+ log.Println(err)
+ http.Error(w, "can't get file url", http.StatusInternalServerError)
+ return
+ }
+ fmt.Fprintln(w, u)
+}