From e039ad968855d18c93c14dadae9f52f0e6e31f70 Mon Sep 17 00:00:00 2001 From: Claudio Ramirez Date: Mon, 8 Feb 2021 19:58:00 +0100 Subject: [PATCH] example for nxadm/tail#6 --- examples/02-closeAndReopen/main.go | 1 + examples/03-consumeJSON/main.go | 54 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+) create mode 100644 examples/03-consumeJSON/main.go diff --git a/examples/02-closeAndReopen/main.go b/examples/02-closeAndReopen/main.go index ed49bcd..e661b65 100644 --- a/examples/02-closeAndReopen/main.go +++ b/examples/02-closeAndReopen/main.go @@ -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 diff --git a/examples/03-consumeJSON/main.go b/examples/03-consumeJSON/main.go new file mode 100644 index 0000000..0d1f6ee --- /dev/null +++ b/examples/03-consumeJSON/main.go @@ -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++ + } +}