Skip to content

Instantly share code, notes, and snippets.

@c-nv-s
Forked from DenoGeek/resumable.go
Created November 26, 2023 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save c-nv-s/5cbc3709345c547a76455f9660ab3cdb to your computer and use it in GitHub Desktop.
Save c-nv-s/5cbc3709345c547a76455f9660ab3cdb to your computer and use it in GitHub Desktop.
// ResumableUpload handles reumable uploads
func ResumableUpload(w http.ResponseWriter, r *http.Request) {
tempFolder := "/path/to/uploads/temp/"
switch r.Method {
case "GET":
resumableIdentifier, _ := r.URL.Query()["resumableIdentifier"]
resumableChunkNumber, _ := r.URL.Query()["resumableChunkNumber"]
path := fmt.Sprintf("%s%s", tempFolder, resumableIdentifier[0])
relativeChunk := fmt.Sprintf("%s%s%s%s", path, "/", "part", resumableChunkNumber[0])
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, os.ModePerm)
}
if _, err := os.Stat(relativeChunk); os.IsNotExist(err) {
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusMethodNotAllowed)
} else {
http.Error(w, "Chunk already exist", http.StatusCreated)
}
default:
r.ParseMultipartForm(10 << 20)
file, _, err := r.FormFile("file")
if err != nil {
print(err.Error())
return
}
defer file.Close()
resumableIdentifier, _ := r.URL.Query()["resumableIdentifier"]
resumableChunkNumber, _ := r.URL.Query()["resumableChunkNumber"]
path := fmt.Sprintf("%s%s", tempFolder, resumableIdentifier[0])
relativeChunk := fmt.Sprintf("%s%s%s%s", path, "/", "part", resumableChunkNumber[0])
if _, err := os.Stat(path); os.IsNotExist(err) {
os.Mkdir(path, os.ModePerm)
}
f, err := os.OpenFile(relativeChunk, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
print(err.Error())
}
defer f.Close()
io.Copy(f, file)
/*
If it is the last chunk, trigger the recombination of chunks
*/
resumableTotalChunks, _ := r.URL.Query()["resumableTotalChunks"]
current, err := strconv.Atoi(resumableChunkNumber[0])
total, err := strconv.Atoi(resumableTotalChunks[0])
if current == total {
print("Combining chunks into one file")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment