I create a tar file in memory:
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
files := map[string][]byte{
"1.txt": []byte("11"),
"2.txt": []byte("2"),
}
for fileName, bStr := range files {
b := []byte(bStr)
hdr := &tar.Header{
Name: fileName,
Mode: 0600,
Size: int64(len(b)),
}
log.Printf("include the file to the tar %+v
", hdr)
if err := tw.WriteHeader(hdr); err != nil {
err := fmt.Errorf("couldn't write a header: %+v", err)
log.Println(err)
return
}
if _, err := tw.Write(b); err != nil {
err := fmt.Errorf("couldn't write file %+v to tar: %+v", fileName, err)
log.Println(err)
return
}
}
if err := tw.Close(); err != nil {
log.Println(err)
return
}
But unable to convert this tar file to bytes. playground 1
b, err := ioutil.ReadAll(tr)
if err != nil {
err = fmt.Errorf("could not read file data")
log.Println(err)
return
}
log.Printf("read %+v bytes", len(b))
It just prints 0 bytes:
2018/06/26 16:57:04 main.go:67: read 0 bytes
But I can read the content of the tar, file by file:
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("Contents of %s:
", hdr.Name)
if _, err := io.Copy(os.Stdout, tr); err != nil {
log.Fatal(err)
}
fmt.Println()
}
It prints
Contents of 2.txt:
2
Contents of 1.txt:
11
as expected.
So it means that my tar file is not empty. I just need to convert it to bytes for further pushing to glcoud storage. But looks like I mess around with readers and writers and can hardly figure out how to convert tar to bytes in the memory.