2019-04-26 10:11:17 +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 metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
// always put all the related things together as in here
|
|
|
|
|
|
|
|
// result stores metrics for a domain
|
|
|
|
// it uses the value mechanics,
|
|
|
|
// because it doesn't have to update anything
|
|
|
|
type result struct {
|
2019-04-26 21:32:20 +03:00
|
|
|
Domain string
|
|
|
|
Visits int
|
|
|
|
TimeSpent int
|
2019-04-26 10:11:17 +03:00
|
|
|
// add more metrics if needed
|
|
|
|
}
|
|
|
|
|
|
|
|
// add adds the metrics of another Result to itself and returns a new Result
|
|
|
|
func (r result) add(other result) result {
|
|
|
|
return result{
|
2019-04-26 21:32:20 +03:00
|
|
|
Domain: r.Domain,
|
|
|
|
Visits: r.Visits + other.Visits,
|
|
|
|
TimeSpent: r.TimeSpent + other.TimeSpent,
|
2019-04-26 10:11:17 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// parse parses a single log line
|
2019-04-26 21:32:20 +03:00
|
|
|
func parse(line string) (r result, err error) {
|
2019-04-26 10:11:17 +03:00
|
|
|
fields := strings.Fields(line)
|
2019-04-26 21:32:20 +03:00
|
|
|
if len(fields) != 3 {
|
2019-04-26 10:11:17 +03:00
|
|
|
err = fmt.Errorf("wrong input: %v", fields)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2019-04-26 21:32:20 +03:00
|
|
|
r.Domain = fields[0]
|
2019-04-26 10:11:17 +03:00
|
|
|
|
2019-04-26 21:32:20 +03:00
|
|
|
r.Visits, err = strconv.Atoi(fields[1])
|
|
|
|
if r.Visits < 0 || err != nil {
|
2019-04-26 10:11:17 +03:00
|
|
|
err = fmt.Errorf("wrong input: %q", fields[1])
|
|
|
|
}
|
|
|
|
|
2019-04-26 21:32:20 +03:00
|
|
|
r.TimeSpent, err = strconv.Atoi(fields[2])
|
|
|
|
if r.TimeSpent < 0 || err != nil {
|
|
|
|
err = fmt.Errorf("wrong input: %q", fields[2])
|
|
|
|
}
|
|
|
|
|
2019-04-26 10:11:17 +03:00
|
|
|
return
|
|
|
|
}
|