Skip to content

Commit e039ad9

Browse files
committed
example for #6
1 parent b266da8 commit e039ad9

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

examples/02-closeAndReopen/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
// Tail a file, print its contents, close it and reopen it.
2+
//
23
// In this example you can add lines to the syslog log by using the logger
34
// command. Exit with Ctrl+C.
45
package main

examples/03-consumeJSON/main.go

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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+
}

0 commit comments

Comments
 (0)