Files
learngo/interfaces/05-log-parser/oop/jsonparser.go

62 lines
1023 B
Go
Raw Normal View History

2019-08-17 15:55:25 +03:00
// For more tutorials: https://bp.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
)
type jsonParser struct {
2019-08-19 20:00:27 +03:00
r io.Reader
2019-08-17 15:55:25 +03:00
}
func newJSONParser(r io.Reader) *jsonParser {
2019-08-19 20:00:27 +03:00
return &jsonParser{r: r}
2019-08-17 15:55:25 +03:00
}
2019-08-19 20:00:27 +03:00
func (p *jsonParser) parse(handle resultFn) error {
2019-08-17 15:55:25 +03:00
defer readClose(p.r)
bytes, err := ioutil.ReadAll(p.r)
if err != nil {
return err
}
2019-08-19 20:00:27 +03:00
return parseJSON(bytes, handle)
2019-08-17 15:55:25 +03:00
}
2019-08-19 20:00:27 +03:00
func parseJSON(bytes []byte, handle resultFn) error {
2019-08-17 15:55:25 +03:00
var rs []struct {
Domain string
Page string
Visits int
Uniques int
}
if err := json.Unmarshal(bytes, &rs); err != nil {
if serr, ok := err.(*json.SyntaxError); ok {
return fmt.Errorf("%v %q", serr, bytes[:serr.Offset])
}
return err
}
for _, r := range rs {
2019-08-19 20:00:27 +03:00
handle(result{
2019-08-17 15:55:25 +03:00
domain: r.Domain,
page: r.Page,
visits: r.Visits,
uniques: r.Uniques,
})
}
return nil
}