example_test.go 2.0 KB

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