github.com/roboticscm/goman@v0.0.0-20210203095141-87c07b4a0a55/src/archive/tar/example_test.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 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() { 17 // Create a buffer to write our archive to. 18 buf := new(bytes.Buffer) 19 20 // Create a new tar archive. 21 tw := tar.NewWriter(buf) 22 23 // Add some files to the archive. 24 var files = []struct { 25 Name, Body string 26 }{ 27 {"readme.txt", "This archive contains some text files."}, 28 {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, 29 {"todo.txt", "Get animal handling licence."}, 30 } 31 for _, file := range files { 32 hdr := &tar.Header{ 33 Name: file.Name, 34 Size: int64(len(file.Body)), 35 } 36 if err := tw.WriteHeader(hdr); err != nil { 37 log.Fatalln(err) 38 } 39 if _, err := tw.Write([]byte(file.Body)); err != nil { 40 log.Fatalln(err) 41 } 42 } 43 // Make sure to check the error on Close. 44 if err := tw.Close(); err != nil { 45 log.Fatalln(err) 46 } 47 48 // Open the tar archive for reading. 49 r := bytes.NewReader(buf.Bytes()) 50 tr := tar.NewReader(r) 51 52 // Iterate through the files in the archive. 53 for { 54 hdr, err := tr.Next() 55 if err == io.EOF { 56 // end of tar archive 57 break 58 } 59 if err != nil { 60 log.Fatalln(err) 61 } 62 fmt.Printf("Contents of %s:\n", hdr.Name) 63 if _, err := io.Copy(os.Stdout, tr); err != nil { 64 log.Fatalln(err) 65 } 66 fmt.Println() 67 } 68 69 // Output: 70 // Contents of readme.txt: 71 // This archive contains some text files. 72 // Contents of gopher.txt: 73 // Gopher names: 74 // George 75 // Geoffrey 76 // Gonzo 77 // Contents of todo.txt: 78 // Get animal handling licence. 79 }