github.com/mdempsky/go@v0.0.0-20151201204031-5dd372bd1e70/src/archive/zip/example_test.go (about) 1 // Copyright 2012 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 zip_test 6 7 import ( 8 "archive/zip" 9 "bytes" 10 "compress/flate" 11 "fmt" 12 "io" 13 "log" 14 "os" 15 ) 16 17 func ExampleWriter() { 18 // Create a buffer to write our archive to. 19 buf := new(bytes.Buffer) 20 21 // Create a new zip archive. 22 w := zip.NewWriter(buf) 23 24 // Add some files to the archive. 25 var files = []struct { 26 Name, Body string 27 }{ 28 {"readme.txt", "This archive contains some text files."}, 29 {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, 30 {"todo.txt", "Get animal handling licence.\nWrite more examples."}, 31 } 32 for _, file := range files { 33 f, err := w.Create(file.Name) 34 if err != nil { 35 log.Fatal(err) 36 } 37 _, err = f.Write([]byte(file.Body)) 38 if err != nil { 39 log.Fatal(err) 40 } 41 } 42 43 // Make sure to check the error on Close. 44 err := w.Close() 45 if err != nil { 46 log.Fatal(err) 47 } 48 } 49 50 func ExampleReader() { 51 // Open a zip archive for reading. 52 r, err := zip.OpenReader("testdata/readme.zip") 53 if err != nil { 54 log.Fatal(err) 55 } 56 defer r.Close() 57 58 // Iterate through the files in the archive, 59 // printing some of their contents. 60 for _, f := range r.File { 61 fmt.Printf("Contents of %s:\n", f.Name) 62 rc, err := f.Open() 63 if err != nil { 64 log.Fatal(err) 65 } 66 _, err = io.CopyN(os.Stdout, rc, 68) 67 if err != nil { 68 log.Fatal(err) 69 } 70 rc.Close() 71 fmt.Println() 72 } 73 // Output: 74 // Contents of README: 75 // This is the source code repository for the Go programming language. 76 } 77 78 func ExampleWriter_RegisterCompressor() { 79 // Override the default Deflate compressor with a higher compression 80 // level. 81 82 // Create a buffer to write our archive to. 83 buf := new(bytes.Buffer) 84 85 // Create a new zip archive. 86 w := zip.NewWriter(buf) 87 88 var fw *flate.Writer 89 90 // Register the deflator. 91 w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { 92 var err error 93 if fw == nil { 94 // Creating a flate compressor for every file is 95 // expensive, create one and reuse it. 96 fw, err = flate.NewWriter(out, flate.BestCompression) 97 } else { 98 fw.Reset(out) 99 } 100 return fw, err 101 }) 102 103 // Proceed to add files to w. 104 }