github.com/4ad/go@v0.0.0-20161219182952-69a12818b605/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 level. 80 81 // Create a buffer to write our archive to. 82 buf := new(bytes.Buffer) 83 84 // Create a new zip archive. 85 w := zip.NewWriter(buf) 86 87 // Register a custom Deflate compressor. 88 w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) { 89 return flate.NewWriter(out, flate.BestCompression) 90 }) 91 92 // Proceed to add files to w. 93 }