github.com/bgentry/go@v0.0.0-20150121062915-6cf5a733d54d/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  	"fmt"
    11  	"io"
    12  	"log"
    13  	"os"
    14  )
    15  
    16  func ExampleWriter() {
    17  	// Create a buffer to write our archive to.
    18  	buf := new(bytes.Buffer)
    19  
    20  	// Create a new zip archive.
    21  	w := zip.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.\nWrite more examples."},
    30  	}
    31  	for _, file := range files {
    32  		f, err := w.Create(file.Name)
    33  		if err != nil {
    34  			log.Fatal(err)
    35  		}
    36  		_, err = f.Write([]byte(file.Body))
    37  		if err != nil {
    38  			log.Fatal(err)
    39  		}
    40  	}
    41  
    42  	// Make sure to check the error on Close.
    43  	err := w.Close()
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  }
    48  
    49  func ExampleReader() {
    50  	// Open a zip archive for reading.
    51  	r, err := zip.OpenReader("testdata/readme.zip")
    52  	if err != nil {
    53  		log.Fatal(err)
    54  	}
    55  	defer r.Close()
    56  
    57  	// Iterate through the files in the archive,
    58  	// printing some of their contents.
    59  	for _, f := range r.File {
    60  		fmt.Printf("Contents of %s:\n", f.Name)
    61  		rc, err := f.Open()
    62  		if err != nil {
    63  			log.Fatal(err)
    64  		}
    65  		_, err = io.CopyN(os.Stdout, rc, 68)
    66  		if err != nil {
    67  			log.Fatal(err)
    68  		}
    69  		rc.Close()
    70  		fmt.Println()
    71  	}
    72  	// Output:
    73  	// Contents of README:
    74  	// This is the source code repository for the Go programming language.
    75  }