...
Source file
src/archive/tar/example_test.go
1
2
3
4
5 package tar_test
6
7 import (
8 "archive/tar"
9 "bytes"
10 "fmt"
11 "io"
12 "log"
13 "os"
14 )
15
16 func Example_minimal() {
17
18 var buf bytes.Buffer
19 tw := tar.NewWriter(&buf)
20 var files = []struct {
21 Name, Body string
22 }{
23 {"readme.txt", "This archive contains some text files."},
24 {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
25 {"todo.txt", "Get animal handling license."},
26 }
27 for _, file := range files {
28 hdr := &tar.Header{
29 Name: file.Name,
30 Mode: 0600,
31 Size: int64(len(file.Body)),
32 }
33 if err := tw.WriteHeader(hdr); err != nil {
34 log.Fatal(err)
35 }
36 if _, err := tw.Write([]byte(file.Body)); err != nil {
37 log.Fatal(err)
38 }
39 }
40 if err := tw.Close(); err != nil {
41 log.Fatal(err)
42 }
43
44
45 tr := tar.NewReader(&buf)
46 for {
47 hdr, err := tr.Next()
48 if err == io.EOF {
49 break
50 }
51 if err != nil {
52 log.Fatal(err)
53 }
54 fmt.Printf("Contents of %s:\n", hdr.Name)
55 if _, err := io.Copy(os.Stdout, tr); err != nil {
56 log.Fatal(err)
57 }
58 fmt.Println()
59 }
60
61
62
63
64
65
66
67
68
69
70
71 }
72
View as plain text