Files
learngo/25-project-log-parser-structs/main.go

82 lines
1.8 KiB
Go
Raw Normal View History

2019-04-23 00:32:25 +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 (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
// domain represents a domain log record
type domain struct {
name string
visits int
}
// parser parses a log file and provides an iterator to iterate upon the domains
//
// the parser struct is carefully crafted to be usable using its zero values except the map field
type parser struct {
2019-04-25 15:38:41 +03:00
sum map[string]domain // visits per unique domain
domains []string // unique domain names
total int // total visits to all domains
lines int // number of parsed lines (for the error messages)
2019-04-23 00:32:25 +03:00
}
func main() {
in := bufio.NewScanner(os.Stdin)
p := parser{
2019-04-25 15:38:41 +03:00
sum: make(map[string]domain),
2019-04-23 00:32:25 +03:00
}
// Scan the standard-in line by line
for in.Scan() {
p.lines++
// Parse the fields
fields := strings.Fields(in.Text())
if len(fields) != 2 {
fmt.Printf("wrong input: %v (line #%d)\n", fields, p.lines)
return
}
name, visits := fields[0], fields[1]
// Sum the total visits per domain
2019-04-24 22:33:45 +03:00
n, err := strconv.Atoi(visits)
if n < 0 || err != nil {
2019-04-23 00:32:25 +03:00
fmt.Printf("wrong input: %q (line #%d)\n", visits, p.lines)
return
}
d := domain{name: name, visits: n}
// Collect the unique domains
2019-04-24 22:33:45 +03:00
if _, ok := p.sum[d.name]; !ok {
2019-04-25 15:38:41 +03:00
p.domains = append(p.domains, name)
2019-04-23 00:32:25 +03:00
}
p.total += d.visits
2019-04-25 15:38:41 +03:00
d.visits += p.sum[name].visits
p.sum[name] = d
2019-04-23 00:32:25 +03:00
}
// Print the visits per domain
2019-04-25 15:38:41 +03:00
for _, name := range p.domains {
d := p.sum[name]
2019-04-23 00:32:25 +03:00
2019-04-25 15:38:41 +03:00
fmt.Printf("%-25s -> %d\n", d.name, d.visits)
2019-04-23 00:32:25 +03:00
}
// Print the total visits for all domains
fmt.Printf("\n%-25s -> %d\n", "TOTAL", p.total)
}