github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/compress/gzip/example_test.go (about) 1 // Copyright 2016 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 gzip_test 6 7 import ( 8 "bytes" 9 "compress/gzip" 10 "fmt" 11 "io" 12 "log" 13 "os" 14 "time" 15 ) 16 17 func Example_writerReader() { 18 var buf bytes.Buffer 19 zw := gzip.NewWriter(&buf) 20 21 // Setting the Header fields is optional. 22 zw.Name = "a-new-hope.txt" 23 zw.Comment = "an epic space opera by George Lucas" 24 zw.ModTime = time.Date(1977, time.May, 25, 0, 0, 0, 0, time.UTC) 25 26 _, err := zw.Write([]byte("A long time ago in a galaxy far, far away...")) 27 if err != nil { 28 log.Fatal(err) 29 } 30 31 if err := zw.Close(); err != nil { 32 log.Fatal(err) 33 } 34 35 zr, err := gzip.NewReader(&buf) 36 if err != nil { 37 log.Fatal(err) 38 } 39 40 fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC()) 41 42 if _, err := io.Copy(os.Stdout, zr); err != nil { 43 log.Fatal(err) 44 } 45 46 if err := zr.Close(); err != nil { 47 log.Fatal(err) 48 } 49 50 // Output: 51 // Name: a-new-hope.txt 52 // Comment: an epic space opera by George Lucas 53 // ModTime: 1977-05-25 00:00:00 +0000 UTC 54 // 55 // A long time ago in a galaxy far, far away... 56 } 57 58 func ExampleReader_Multistream() { 59 var buf bytes.Buffer 60 zw := gzip.NewWriter(&buf) 61 62 var files = []struct { 63 name string 64 comment string 65 modTime time.Time 66 data string 67 }{ 68 {"file-1.txt", "file-header-1", time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC), "Hello Gophers - 1"}, 69 {"file-2.txt", "file-header-2", time.Date(2007, time.March, 2, 4, 5, 6, 1, time.UTC), "Hello Gophers - 2"}, 70 } 71 72 for _, file := range files { 73 zw.Name = file.name 74 zw.Comment = file.comment 75 zw.ModTime = file.modTime 76 77 if _, err := zw.Write([]byte(file.data)); err != nil { 78 log.Fatal(err) 79 } 80 81 if err := zw.Close(); err != nil { 82 log.Fatal(err) 83 } 84 85 zw.Reset(&buf) 86 } 87 88 zr, err := gzip.NewReader(&buf) 89 if err != nil { 90 log.Fatal(err) 91 } 92 93 for { 94 zr.Multistream(false) 95 fmt.Printf("Name: %s\nComment: %s\nModTime: %s\n\n", zr.Name, zr.Comment, zr.ModTime.UTC()) 96 97 if _, err := io.Copy(os.Stdout, zr); err != nil { 98 log.Fatal(err) 99 } 100 101 fmt.Print("\n\n") 102 103 err = zr.Reset(&buf) 104 if err == io.EOF { 105 break 106 } 107 if err != nil { 108 log.Fatal(err) 109 } 110 } 111 112 if err := zr.Close(); err != nil { 113 log.Fatal(err) 114 } 115 116 // Output: 117 // Name: file-1.txt 118 // Comment: file-header-1 119 // ModTime: 2006-02-01 03:04:05 +0000 UTC 120 // 121 // Hello Gophers - 1 122 // 123 // Name: file-2.txt 124 // Comment: file-header-2 125 // ModTime: 2007-03-02 04:05:06 +0000 UTC 126 // 127 // Hello Gophers - 2 128 }