Files
learngo/logparser/v5/pipe/jsonlog.go

50 lines
927 B
Go
Raw Permalink Normal View History

2019-08-17 15:55:25 +03:00
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
2019-10-30 19:34:44 +03:00
// For more tutorials : https://learngoprogramming.com
// In-person training : https://www.linkedin.com/in/inancgumus/
// Follow me on twitter: https://twitter.com/inancgumus
2019-08-17 15:55:25 +03:00
2019-08-28 23:46:42 +03:00
package pipe
2019-08-17 15:55:25 +03:00
import (
"encoding/json"
"io"
)
2019-08-28 23:46:42 +03:00
// JSON parses json records.
type JSON struct {
2019-08-26 14:37:58 +03:00
reader io.Reader
2019-08-17 15:55:25 +03:00
}
2019-08-28 23:46:42 +03:00
// NewJSONLog creates a json parser.
func NewJSONLog(r io.Reader) *JSON {
return &JSON{reader: r}
2019-08-17 15:55:25 +03:00
}
2019-08-29 16:08:46 +03:00
// Each sends the records from a reader to upstream.
2019-08-28 23:46:42 +03:00
func (j *JSON) Each(yield func(Record) error) error {
2019-08-26 14:37:58 +03:00
defer readClose(j.reader)
2019-08-17 15:55:25 +03:00
2019-08-29 18:27:31 +03:00
// Use the same record for unmarshaling.
var r Record
2019-08-28 23:46:42 +03:00
dec := json.NewDecoder(j.reader)
2019-08-17 15:55:25 +03:00
2019-08-26 21:52:47 +03:00
for {
err := dec.Decode(&r)
if err == io.EOF {
break
}
if err != nil {
return err
2019-08-17 15:55:25 +03:00
}
2019-08-28 23:46:42 +03:00
if err := yield(r); err != nil {
return err
}
2019-08-17 15:55:25 +03:00
}
2019-08-28 23:46:42 +03:00
2019-08-17 15:55:25 +03:00
return nil
}