Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"bufio"
"fmt"
"log"
"os"
"runtime"
"strings"
"sync"
)
func init() {
runtime.GOMAXPROCS(runtime.NumCPU())
}
func main() {
file, err := os.Open("muestra.log")
if err != nil {
log.Fatalf("open file: %v", err)
}
defer file.Close()
// Channels for the data
lines := make(chan string)
results := make(chan map[string]string)
// This will tell us when we finished with all the lines
var wg sync.WaitGroup
go func() {
scanner := bufio.NewScanner(file)
for scanner.Scan() {
wg.Add(1)
lines <- scanner.Text()
}
if err := scanner.Err(); err != nil {
log.Fatalf("scanning file: %v", err)
}
close(lines)
}()
keys := []string{
"RemoteHost",
"RemoteLogName",
"RemoteUser",
"TimeReceived",
"RequestMethod",
"RequestURL",
"RequestHTTP",
"Status",
"ResponseBytes",
"RequestHeaderUserAgent",
"Cached",
"ContentType",
"Node",
"RTime",
"Company",
"Referrer",
}
// This will be invoked every time a line is available
for line := range lines {
go func(line string) {
// Free up a WaitGroup
defer wg.Done()
r := make(map[string]string)
// Split the line
segments := strings.Split(line, " ")
for i, k := range keys {
// Prevent index out of range runtime error
if i > len(segments) {
break
}
switch k {
case "TimeReceived":
r[k] = strings.Trim(segments[i], "[]")
case "RequestMethod":
r[k] = strings.TrimLeft(segments[i], "\"")
case "RequestHTTP":
r[k] = strings.TrimRight(segments[i], "\"")
default:
r[k] = segments[i]
}
}
results <- r
}(line)
}
// Close the results channell once all the data was consumed
go func() {
wg.Wait()
close(results)
}()
// Read all your sweet results here. Do whatever you want with them
count := 0
for range results {
count++
}
// To read your result:
// for r := range results {
// // Do something witht r
// }
fmt.Printf("Processed %v lines\n", count)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.