forked from ulikunitz/xz
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_test.go
More file actions
79 lines (73 loc) · 2.06 KB
/
Copy pathexample_test.go
File metadata and controls
79 lines (73 loc) · 2.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Copyright 2014-2022 Ulrich Kunitz. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xz_test
import (
"bufio"
"fmt"
"io"
"log"
"os"
"path/filepath"
"github.com/forkcloser/xz"
)
// These examples are the package's front page on pkg.go.dev, so they are
// written the way calling code should be written: nothing is abandoned
// half-closed, and the errors that matter are all checked. In particular
// log.Fatal is only reached before anything needs cleaning up, because it
// exits without running deferred calls.
func ExampleReader() {
f, err := os.Open("fox.xz")
if err != nil {
log.Fatalf("os.Open(%q) error %s", "fox.xz", err)
}
defer func() {
if err := f.Close(); err != nil {
log.Printf("f.Close() error %s", err)
}
}()
r, err := xz.NewReader(bufio.NewReader(f))
if err != nil {
log.Printf("xz.NewReader(f) error %s", err)
return
}
if _, err = io.Copy(os.Stdout, r); err != nil {
log.Printf("io.Copy error %s", err)
return
}
// Output:
// The quick brown fox jumps over the lazy dog.
}
func ExampleWriter() {
// A temporary path keeps the example from dropping a file into whatever
// directory it is run from — which, when it runs as a test, is the
// package source directory.
name := filepath.Join(os.TempDir(), "example.xz")
f, err := os.Create(name)
if err != nil {
log.Fatalf("os.Create(%q) error %s", name, err)
}
defer func() { _ = os.Remove(name) }()
defer func() {
if err := f.Close(); err != nil {
log.Printf("f.Close() error %s", err)
}
}()
w, err := xz.NewWriter(f)
if err != nil {
log.Printf("xz.NewWriter(f) error %s", err)
return
}
if _, err = fmt.Fprintln(w, "The brown fox jumps over the lazy dog."); err != nil {
log.Printf("fmt.Fprintln error %s", err)
return
}
// Close finishes the compressed stream. Skipping it, or ignoring what it
// returns, is how a truncated archive gets written without anyone
// noticing.
if err = w.Close(); err != nil {
log.Printf("w.Close() error %s", err)
return
}
// Output:
}