Source file
src/archive/zip/example_test.go
1
2
3
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
19 buf := new(bytes.Buffer)
20
21
22 w := zip.NewWriter(buf)
23
24
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
44 err := w.Close()
45 if err != nil {
46 log.Fatal(err)
47 }
48 }
49
50 func ExampleReader() {
51
52 r, err := zip.OpenReader("testdata/readme.zip")
53 if err != nil {
54 log.Fatal(err)
55 }
56 defer r.Close()
57
58
59
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
74
75
76 }
77
78 func ExampleWriter_RegisterCompressor() {
79
80
81
82 buf := new(bytes.Buffer)
83
84
85 w := zip.NewWriter(buf)
86
87
88 w.RegisterCompressor(zip.Deflate, func(out io.Writer) (io.WriteCloser, error) {
89 return flate.NewWriter(out, flate.BestCompression)
90 })
91
92
93 }
94
View as plain text