github.com/dayvar14/tail@v0.0.0-20240222011302-f530c4fa0c9f/examples/03-consumeJSON/main.go (about) 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 "io/ioutil" 12 "os" 13 "strconv" 14 15 "github.com/nxadm/tail" 16 ) 17 18 type jsonStruct struct { 19 Counter string `json:"counter"` 20 } 21 22 func main() { 23 file, err := ioutil.TempFile(os.TempDir(), "") 24 if err != nil { 25 panic(err) 26 } 27 fmt.Println(file.Name()) 28 defer file.Close() 29 defer os.Remove(file.Name()) 30 31 t, err := tail.TailFile(file.Name(), tail.Config{Follow: true}) 32 if err != nil { 33 panic(err) 34 } 35 36 go createJSON(file) 37 var js jsonStruct 38 for line := range t.Lines { 39 fmt.Printf("JSON: " + line.Text + "\n") 40 41 err := json.Unmarshal([]byte(line.Text), &js) 42 if err != nil { 43 panic(err) 44 } 45 fmt.Printf("JSON counter field: " + js.Counter + "\n") 46 } 47 } 48 49 func createJSON(file *os.File) { 50 var counter int 51 for { 52 file.WriteString("{ \"counter\": \"" + strconv.Itoa(counter) + "\"}\n") 53 counter++ 54 } 55 }