Skip to content

Instantly share code, notes, and snippets.

@Jimeux
Created February 3, 2019 06:42
Show Gist options
  • Save Jimeux/d0f005bd2713b7f12e428073818a0bd3 to your computer and use it in GitHub Desktop.
Save Jimeux/d0f005bd2713b7f12e428073818a0bd3 to your computer and use it in GitHub Desktop.
io.Pipeによるファイルのアップロード
package main
import (
"io"
"log"
"mime/multipart"
"net/http"
"os"
)
func main() {
url := "http://localhost:3000/upload"
fieldName := "file"
fileName := "hello.txt"
file, err := os.Open(fileName)
handleError(err)
pr, pw := io.Pipe()
// io.PipeWriterをmultipart.Writerに渡す
mw := multipart.NewWriter(pw)
// Goルーチンを開始し非同期でpwに書き込む
go func() {
// prの処理が正常に終わるように必ずpwをクローズする
defer pw.Close()
defer mw.Close()
fw, err := mw.CreateFormFile(fieldName, fileName)
if err != nil {
return
}
if _, err := io.Copy(fw, file); err != nil {
return
}
}()
// io.PipeReaderをHTTPリクエストのボディに渡す
resp, err := http.Post(url, mw.FormDataContentType(), pr)
handleError(err)
err = resp.Body.Close()
handleError(err)
}
func handleError(err error) {
if err != nil {
log.Fatal(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment