Skip to content

Instantly share code, notes, and snippets.

@cgwalters
Created May 7, 2021 15:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cgwalters/a99274d7048b1c5c62ddce4ddc95f14c to your computer and use it in GitHub Desktop.
Save cgwalters/a99274d7048b1c5c62ddce4ddc95f14c to your computer and use it in GitHub Desktop.
Demonstrate corrupted concurrent Go tar writing
package main
import (
"archive/tar"
"bytes"
"fmt"
"io"
"log"
"os"
"sync"
)
func main() {
// Create and add some files to the archive.
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
var files = []struct {
Name, Body string
}{
{"readme.txt", "This archive contains some text files."},
{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
{"todo.txt", "Get animal handling license."},
}
var wg sync.WaitGroup
for _, file := range files {
wg.Add(1)
go func() {
defer wg.Done()
hdr := &tar.Header{
Name: file.Name,
Mode: 0600,
Size: int64(len(file.Body)),
}
if err := tw.WriteHeader(hdr); err != nil {
log.Fatal(err)
}
if _, err := tw.Write([]byte(file.Body)); err != nil {
log.Fatal(err)
}
}()
}
wg.Wait()
if err := tw.Close(); err != nil {
log.Fatal(err)
}
// Open and iterate through the files in the archive.
tr := tar.NewReader(&buf)
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive
}
if err != nil {
log.Fatal(err)
}
fmt.Printf("Contents of %s:\n", hdr.Name)
if _, err := io.Copy(os.Stdout, tr); err != nil {
log.Fatal(err)
}
fmt.Println()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment