Files
learngo/29-interfaces/logparser-pkg/report/result.go

61 lines
1.4 KiB
Go
Raw Normal View History

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/
//
2019-05-10 14:20:58 +03:00
package report
2019-04-26 10:11:17 +03:00
import (
"fmt"
"strconv"
"strings"
)
// always put all the related things together as in here
2019-05-10 14:20:58 +03:00
// Result stores metrics for a domain
2019-04-26 10:11:17 +03:00
// it uses the value mechanics,
// because it doesn't have to update anything
2019-05-10 14:20:58 +03:00
type Result struct {
Domain string `json:"domain"`
Visits int `json:"visits"`
TimeSpent int `json:"time_spent"`
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
2019-05-10 14:20:58 +03:00
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-05-10 14:20:58 +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-05-10 14:20:58 +03:00
return r, fmt.Errorf("missing fields: %v", fields)
2019-04-26 10:11:17 +03:00
}
2019-05-10 14:20:58 +03:00
f := new(field)
2019-04-26 21:32:20 +03:00
r.Domain = fields[0]
2019-05-10 14:20:58 +03:00
r.Visits = f.atoi("visits", fields[1])
r.TimeSpent = f.atoi("time spent", fields[2])
return r, f.err
}
2019-04-26 10:11:17 +03:00
2019-05-10 14:20:58 +03:00
// field helps for field parsing
type field struct{ err error }
2019-04-26 10:11:17 +03:00
2019-05-10 14:20:58 +03:00
func (f *field) atoi(name, val string) int {
n, err := strconv.Atoi(val)
if n < 0 || err != nil {
f.err = fmt.Errorf("incorrect %s: %q", name, val)
2019-04-26 21:32:20 +03:00
}
2019-05-10 14:20:58 +03:00
return n
2019-04-26 10:11:17 +03:00
}