go - Download a zip file using io.Pipe() read/write golang -


i trying stream out bytes of zip file using io.pipe() function in golang. using pipe reader read bytes of each file in zip , stream out , use pipe writer write bytes in response object.

func main() {   r, w := io.pipe()  // go routine make write/read non-blocking   go func() {      defer w.close()      bytes, err := readbytesforeachfilefromthezip()      err := json.newencoder(w).encode(bytes)     handleerr(err)   }() 

this not working implementation structure of trying achieve. don't want use ioutil.readall since file going large , pipe() me avoid bringing data memory. can working implementation using io.pipe() ?

i made work using golang io.pipe().the pipewriter writes byte pipe in chunks , pipereader reader other end. reason using go-routine have non-blocking write operation while simultaneous reads happen form pipe.

note: it's important close pipe writer (w.close()) send eof on stream otherwise not close stream.

func downloadzip() ([]byte, error) {     r, w := io.pipe()      defer r.close()     defer w.close()      zip, err := os.stat("temp.zip")     if err != nil{         return nil, err     }      go func(){          f, err := os.open(zip.name())         if err != nil {             return          }          buf := make([]byte, 1024)         {             chunk, err := f.read(buf)             if err != nil && err != io.eof {                 panic(err)             }             if chunk == 0 {                 break             }              if _, err := w.write(buf[:chunk]); err != nil{                 return             }          }          w.close()     }()      body, err := ioutil.readall(r)     if err != nil {         return nil, err     }     return body, nil  } 

please let me know if has way of doing it.


Comments

Popular posts from this blog

sql server - Cannot query correctly (MSSQL - PHP - JSON) -

php - trouble displaying mysqli database results in correct order -

C++ Linked List -