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) }