Files
learngo/interfaces/log-parser/oop/pipeline.go

79 lines
1.3 KiB
Go
Raw Normal View History

2019-08-26 14:37:58 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
2019-08-26 21:52:47 +03:00
"fmt"
2019-08-26 14:37:58 +03:00
"os"
"strings"
)
type resultFn func(result)
2019-08-26 21:52:47 +03:00
type iterator interface{ each(resultFn) error }
type digester interface{ digest(iterator) error }
2019-08-26 14:37:58 +03:00
2019-08-26 21:52:47 +03:00
type transform interface {
digester
2019-08-26 14:37:58 +03:00
iterator
}
2019-08-26 21:52:47 +03:00
type pipeline struct {
src iterator
trans []transform
dst digester
2019-08-26 14:37:58 +03:00
}
2019-08-26 21:52:47 +03:00
func (p *pipeline) run() error {
defer func() {
n := p.src.(*logCount).count()
fmt.Printf("%d records processed.\n", n)
}()
last := p.src
for _, t := range p.trans {
if err := t.digest(last); err != nil {
return err
}
last = t
}
return p.dst.digest(last)
2019-08-26 14:37:58 +03:00
}
2019-08-26 21:52:47 +03:00
func newPipeline(src iterator, dst digester, t ...transform) *pipeline {
2019-08-26 14:37:58 +03:00
return &pipeline{
2019-08-26 21:52:47 +03:00
src: &logCount{iterator: src},
dst: dst,
trans: t,
2019-08-26 14:37:58 +03:00
}
}
// fromFile generates a default report
2019-08-26 21:52:47 +03:00
func fromFile(path string) (*pipeline, error) {
2019-08-26 14:37:58 +03:00
f, err := os.Open(path)
if err != nil {
2019-08-26 21:52:47 +03:00
return nil, err
2019-08-26 14:37:58 +03:00
}
var src iterator
switch {
case strings.HasSuffix(path, ".txt"):
src = newTextLog(f)
2019-08-26 21:52:47 +03:00
case strings.HasSuffix(path, ".jsonl"):
2019-08-26 14:37:58 +03:00
src = newJSONLog(f)
}
2019-08-26 21:52:47 +03:00
return newPipeline(
src,
newTextReport(),
groupBy(domainGrouper),
), nil
2019-08-26 14:37:58 +03:00
}