Files
learngo/23-project-log-parser/02-project-log-parser/main.go

74 lines
1.5 KiB
Go
Raw Normal View History

2019-04-12 16:03:10 +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"
2019-04-26 00:26:36 +03:00
"sort"
2019-04-12 16:03:10 +03:00
"strconv"
"strings"
)
func main() {
var (
2019-04-26 00:26:36 +03:00
sum map[string]int // total visits per 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-12 16:03:10 +03:00
)
2019-04-26 00:26:36 +03:00
sum = make(map[string]int)
2019-04-12 16:03:10 +03:00
// Scan the standard-in line by line
2019-04-26 00:26:36 +03:00
in := bufio.NewScanner(os.Stdin)
for in.Scan() {
lines++
2019-04-12 16:03:10 +03:00
// Parse the fields
fields := strings.Fields(in.Text())
if len(fields) != 2 {
2019-04-26 00:26:36 +03:00
fmt.Printf("wrong input: %v (line #%d)\n", fields, lines)
2019-04-12 16:03:10 +03:00
return
}
// Sum the total visits per domain
2019-04-26 00:26:36 +03:00
visits, err := strconv.Atoi(fields[1])
if visits < 0 || err != nil {
fmt.Printf("wrong input: %q (line #%d)\n", fields[1], lines)
2019-04-12 16:03:10 +03:00
return
}
2019-04-26 00:26:36 +03:00
2019-04-26 01:20:41 +03:00
domain := fields[0]
2019-04-26 00:26:36 +03:00
// Collect the unique domains
2019-04-26 01:20:41 +03:00
if _, ok := sum[domain]; !ok {
domains = append(domains, domain)
2019-04-26 00:26:36 +03:00
}
// Keep track of total and per domain visits
total += visits
2019-04-26 01:20:41 +03:00
sum[domain] += visits
2019-04-12 16:03:10 +03:00
}
// Print the visits per domain
2019-04-26 00:26:36 +03:00
sort.Strings(domains)
fmt.Printf("%-30s %10s\n", "DOMAIN", "VISITS")
fmt.Println(strings.Repeat("-", 45))
2019-04-12 16:03:10 +03:00
2019-04-26 01:20:41 +03:00
for _, domain := range domains {
visits := sum[domain]
fmt.Printf("%-30s %10d\n", domain, visits)
2019-04-12 16:03:10 +03:00
}
// Print the total visits for all domains
2019-04-26 00:26:36 +03:00
fmt.Printf("\n%-30s %10d\n", "TOTAL", total)
2019-04-12 16:03:10 +03:00
}