forked from powerman/tail
/
example_test.go
43 lines (34 loc) · 893 Bytes
/
example_test.go
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
package tail_test
import (
"context"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"time"
"github.com/powerman/tail"
)
func Example() {
f, _ := ioutil.TempFile("", "gotest")
_, _ = f.Write([]byte("first"))
ctx, cancel := context.WithCancel(context.Background())
t := tail.Follow(ctx, tail.LoggerFunc(log.Printf), f.Name(),
tail.PollTimeout(2*time.Second)) // increase timeout to avoid error from io.Copy
go func() {
time.Sleep(time.Second) // ensure tail has started
_, _ = f.Write([]byte("second\n"))
_ = os.Remove(f.Name())
time.Sleep(time.Second) // ensure tail notice removed file
_, _ = f.Write([]byte("third\n"))
f.Close()
time.Sleep(time.Second) // ensure tail read file before being cancelled
cancel() // tell tail to cancel and return io.EOF
}()
_, err := io.Copy(os.Stdout, t)
fmt.Println("err:", err)
// Output:
// second
// third
// err: <nil>
}