...

Source file src/github.com/klauspost/compress/zip/example_test.go

Documentation: github.com/klauspost/compress/zip

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

View as plain text