Last active
September 27, 2022 08:42
-
-
Save yakuter/7e5f9c149c6e02a24e0878e42ddec446 to your computer and use it in GitHub Desktop.
Multipart and Pipe file stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This example shows how to send files via pipe using multipart package | |
package main | |
import ( | |
"errors" | |
"fmt" | |
"io" | |
"mime/multipart" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
pipeReader, pipeWriter, err := os.Pipe() | |
if err != nil { | |
panic(err) | |
} | |
defer pipeReader.Close() | |
form := multipart.NewWriter(pipeWriter) | |
defer form.Close() | |
go func() { | |
defer pipeWriter.Close() | |
files := []string{"file1.txt", "file2.txt"} | |
for i := range files { | |
filePart, err := form.CreateFormFile("file", files[i]) | |
if err != nil { | |
panic(err) | |
} | |
copyToWriter(filePart, files[i]) | |
} | |
}() | |
reader := multipart.NewReader(pipeReader, form.Boundary()) | |
for { | |
part, err := reader.NextPart() | |
if err != nil { | |
break | |
} | |
fileName := filepath.Join("./uploads/" + part.FileName()) | |
copyToFile(fileName, part) | |
} | |
} | |
func copyToWriter(dst io.Writer, src string) { | |
file, err := os.Open(src) | |
if err != nil { | |
panic(err) | |
} | |
defer file.Close() | |
_, err = io.Copy(dst, file) | |
if err != nil { | |
panic(err) | |
} | |
} | |
func copyToFile(dst string, src io.Reader) { | |
tempFile, err := os.Create(dst) | |
if err != nil { | |
panic(err) | |
} | |
defer tempFile.Close() | |
_, err = io.Copy(tempFile, src) | |
if err != nil { | |
if errors.Is(err, io.ErrUnexpectedEOF) { | |
fmt.Println("File upload complete") | |
os.Exit(0) | |
} | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment