File tree Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Expand file tree Collapse file tree 2 files changed +55
-0
lines changed Original file line number Diff line number Diff line change 1
1
// Tail a file, print its contents, close it and reopen it.
2
+ //
2
3
// In this example you can add lines to the syslog log by using the logger
3
4
// command. Exit with Ctrl+C.
4
5
package main
Original file line number Diff line number Diff line change
1
+ // Consume and unmarshall JSON.
2
+ //
3
+ // In this example JSON lines are added by createJSON in a tight loop.
4
+ // Each line is unmarshalled and a field printed.
5
+ // Exit with Ctrl+C.
6
+ package main
7
+
8
+ import (
9
+ "encoding/json"
10
+ "fmt"
11
+ "github.com/nxadm/tail"
12
+ "io/ioutil"
13
+ "os"
14
+ "strconv"
15
+ )
16
+
17
+ type jsonStruct struct {
18
+ Counter string `json:"counter"`
19
+ }
20
+
21
+ func main () {
22
+ file , err := ioutil .TempFile (os .TempDir (), "" )
23
+ if err != nil {
24
+ panic (err )
25
+ }
26
+ fmt .Println (file .Name ())
27
+ defer file .Close ()
28
+ defer os .Remove (file .Name ())
29
+
30
+ t , err := tail .TailFile (file .Name (), tail.Config {Follow : true })
31
+ if err != nil {
32
+ panic (err )
33
+ }
34
+
35
+ go createJSON (file )
36
+ var js jsonStruct
37
+ for line := range t .Lines {
38
+ fmt .Printf ("JSON: " + line .Text + "\n " )
39
+
40
+ err := json .Unmarshal ([]byte (line .Text ), & js )
41
+ if err != nil {
42
+ panic (err )
43
+ }
44
+ fmt .Printf ("JSON counter field: " + js .Counter + "\n " )
45
+ }
46
+ }
47
+
48
+ func createJSON (file * os.File ) {
49
+ var counter int
50
+ for {
51
+ file .WriteString ("{ \" counter\" : \" " + strconv .Itoa (counter ) + "\" }\n " )
52
+ counter ++
53
+ }
54
+ }
You can’t perform that action at this time.
0 commit comments