Skip to content

Commit

Permalink
example for #6 (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
nxadm committed Feb 8, 2021
1 parent b266da8 commit ff05002
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/02-closeAndReopen/main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
// Tail a file, print its contents, close it and reopen it.
//
// In this example you can add lines to the syslog log by using the logger
// command. Exit with Ctrl+C.
package main
Expand Down
54 changes: 54 additions & 0 deletions examples/03-consumeJSON/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Consume and unmarshall JSON.
//
// In this example JSON lines are added by createJSON in a tight loop.
// Each line is unmarshalled and a field printed.
// Exit with Ctrl+C.
package main

import (
"encoding/json"
"fmt"
"github.com/nxadm/tail"
"io/ioutil"
"os"
"strconv"
)

type jsonStruct struct {
Counter string `json:"counter"`
}

func main() {
file, err := ioutil.TempFile(os.TempDir(), "")
if err != nil {
panic(err)
}
fmt.Println(file.Name())
defer file.Close()
defer os.Remove(file.Name())

t, err := tail.TailFile(file.Name(), tail.Config{Follow: true})
if err != nil {
panic(err)
}

go createJSON(file)
var js jsonStruct
for line := range t.Lines {
fmt.Printf("JSON: " + line.Text + "\n")

err := json.Unmarshal([]byte(line.Text), &js)
if err != nil {
panic(err)
}
fmt.Printf("JSON counter field: " + js.Counter + "\n")
}
}

func createJSON(file *os.File) {
var counter int
for {
file.WriteString("{ \"counter\": \"" + strconv.Itoa(counter) + "\"}\n")
counter++
}
}

0 comments on commit ff05002

Please sign in to comment.