Was reading up on the use of io.Pipe to reduce allocation (no need to assign cmd.Stdout
to bytes.Buffer). I couldn't get the following to work and appreciate if greatly on how can i use io.Pipe to get output from exec.command to make http mutliform post request.
func main() {
cmd := exec.Command("convert", "test.png", "-resize" "30x30", "png:-")
bodyReader, bodyWriter := io.Pipe()
cmd.Stdout = bodyWriter
formWriter := multipart.NewWriter(bodyWriter)
go func() {
cmd.Run()
partWriter, err := formWriter.CreateFormFile("file", "file")
if err != nil {
fmt.Println("form writer create error")
return
}
_, err = io.Copy(partWriter, bodyReader)
if err != nil {
fmt.Println("io copy error")
return
}
formWriter.Close()
bodyWriter.Close()
}()
url := "http://example.com/upload"
req, _ := http.NewRequest(http.MethodPost, url, bodyReader)
req.Header.Set("Content-Type", formWriter.FormDataContentType())
resp, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Println("htttp do error")
return
}
fmt.Println(resp.StatusCode)
respBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("read error")
return
}
fmt.Println("Result:", string(respBody))
}
Using debugging tool, it just just hang at resp, err := http.DefaultClient.Do(req)
and eventually the following output.
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x10 pc=0x1218c3b]
goroutine 1 [running]:
main.main()