github.com/laher/argo@v0.0.0-20140722103944-11d91c83cc0f/ar/example_test.go (about) 1 // Copyright 2013 Am Laher. 2 // This code is adapted from code within the Go tree. 3 // See Go's licence information below: 4 // 5 // Copyright 2009 The Go Authors. All rights reserved. 6 // Use of this source code is governed by a BSD-style 7 // license that can be found in the LICENSE file. 8 9 package ar_test 10 11 import ( 12 "bytes" 13 "fmt" 14 "github.com/laher/argo/ar" 15 "io" 16 "log" 17 "os" 18 ) 19 20 func Example() { 21 // Create a buffer to write our archive to. 22 wtr := new(bytes.Buffer) 23 24 // Create a new ar archive. 25 aw := ar.NewWriter(wtr) 26 27 // Add some files to the archive. 28 var files = []struct { 29 Name, Body string 30 }{ 31 {"readme.txt", "This archive contains some text files."}, 32 {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, 33 {"todo.txt", "Get animal handling licence."}, 34 } 35 for _, file := range files { 36 hdr := &ar.Header{ 37 Name: file.Name, 38 Size: int64(len(file.Body)), 39 } 40 if err := aw.WriteHeader(hdr); err != nil { 41 log.Fatalln(err) 42 } 43 if _, err := aw.Write([]byte(file.Body)); err != nil { 44 log.Fatalln(err) 45 } 46 } 47 // Make sure to check the error on Close. 48 if err := aw.Close(); err != nil { 49 log.Fatalln(err) 50 } 51 52 // Open the ar archive for reading. 53 rdr := bytes.NewReader(wtr.Bytes()) 54 55 arr, err := ar.NewReader(rdr) 56 if err != nil { 57 log.Fatalln(err) 58 } 59 60 // Iterate through the files in the archive. 61 for { 62 hdr, err := arr.Next() 63 if err == io.EOF { 64 // end of ar archive 65 break 66 } 67 if err != nil { 68 log.Fatalln(err) 69 } 70 fmt.Printf("Contents of %s:\n", hdr.Name) 71 if _, err := io.Copy(os.Stdout, arr); err != nil { 72 log.Fatalln(err) 73 } 74 fmt.Println() 75 } 76 77 // Output: 78 // Contents of readme.txt: 79 // This archive contains some text files. 80 // Contents of gopher.txt: 81 // Gopher names: 82 // George 83 // Geoffrey 84 // Gonzo 85 // Contents of todo.txt: 86 // Get animal handling licence. 87 }