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

83 lines
1.6 KiB
Go
Raw Normal View History

2019-08-17 15:55:25 +03:00
package main
2019-08-26 21:52:47 +03:00
import (
"encoding/json"
2019-08-28 13:09:54 +03:00
"errors"
2019-08-26 21:52:47 +03:00
"fmt"
"strconv"
"strings"
)
2019-08-19 20:00:27 +03:00
const fieldsLength = 4
2019-08-17 15:55:25 +03:00
type result struct {
domain string
page string
visits int
uniques int
}
2019-08-28 12:46:43 +03:00
func (r result) sum(other result) result {
2019-08-17 15:55:25 +03:00
r.visits += other.visits
r.uniques += other.uniques
return r
}
2019-08-26 21:52:47 +03:00
// UnmarshalText to a *result
func (r *result) UnmarshalText(p []byte) (err error) {
fields := strings.Fields(string(p))
if len(fields) != fieldsLength {
return fmt.Errorf("wrong number of fields %q", fields)
}
r.domain, r.page = fields[0], fields[1]
2019-08-28 12:46:43 +03:00
if r.visits, err = parseStr("visits", fields[2]); err != nil {
return err
2019-08-26 21:52:47 +03:00
}
2019-08-28 12:46:43 +03:00
if r.uniques, err = parseStr("uniques", fields[3]); err != nil {
return err
2019-08-26 21:52:47 +03:00
}
2019-08-28 13:09:54 +03:00
return validate(*r)
2019-08-28 12:46:43 +03:00
}
2019-08-26 21:52:47 +03:00
// UnmarshalJSON to a *result
func (r *result) UnmarshalJSON(data []byte) error {
var re struct {
Domain string
Page string
Visits int
Uniques int
}
if err := json.Unmarshal(data, &re); err != nil {
return err
}
*r = result{re.Domain, re.Page, re.Visits, re.Uniques}
2019-08-28 13:09:54 +03:00
return validate(*r)
}
2019-08-26 21:52:47 +03:00
2019-08-28 13:09:54 +03:00
// parseStr helps UnmarshalText for string to positive int parsing
func parseStr(name, v string) (int, error) {
n, err := strconv.Atoi(v)
if err != nil {
return 0, fmt.Errorf("result.UnmarshalText %q: %v", name, err)
}
return n, nil
}
func validate(r result) (err error) {
switch {
case r.domain == "":
err = errors.New("result.domain cannot be empty")
case r.page == "":
err = errors.New("result.page cannot be empty")
case r.visits < 0:
err = errors.New("result.visits cannot be negative")
case r.uniques < 0:
err = errors.New("result.uniques cannot be negative")
}
return
2019-08-26 21:52:47 +03:00
}