golang scanner read until end of reader - string

I have a bufio scanner on a StringReader. After I reach a certain line on the Scanner output, I want to read until the end of the reader. Is there any way to achieve this using a simpler way, other than the commented code ?
s := `1
2
3
4
5
6
7`
beyond5 := ""
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
if strings.Contains(scanner.Text(), "5") {
// Read all lines until EOF from scanner
// and store in beyond5
// for scanner.Scan() {
// beyond5 += scanner.Text()
// beyond5 += "\n"
// }
break
}
}
log.Println(beyond5)

It seems such an operation is not possible at all with the scanner. We need to use the bufio reader only. The code is:
s := `1
2
3
4
5
6
7`
beyond5 := ""
r := strings.NewReader(s)
reader := bufio.NewReader(r)
for {
line, err := reader.ReadString('\n')
if err != nil {
log.Fatal(err)
}
if strings.Contains(line, "5") {
b, _ := ioutil.ReadAll(reader)
beyond5 = string(b)
break
}
}
log.Println(beyond5)

Is this that you want? :-)
s := `1
2
3
4
5
6
7`
var beyond5 string
if strings.Contains(s, "5") {
scanner := bufio.NewScanner(strings.NewReader(s))
for scanner.Scan() {
beyond5 += scanner.Text()
}
}
beyond5 += "\n"
log.Println(beyond5)
UPDATE: My solution is similar to #abhink's solution, however, they are different solutions
I have used Split method, this method set split (private) property that it is SplitFunc type. And this is my implementation:
var canPass bool
func mySplit(data []byte, atEOF bool) (advance int, token []byte, err error) {
for pos, value := range data {
if (value < '6' && !canPass) || (value < '0' || value > '9') {
continue
}
canPass = true
return pos+1, data[pos : pos + 1], nil
}
return 0, nil, nil
}
Now, you must use Split method, send it mySplit as parameter.
scanner.Split(mySplit)
And you do a simple for with scanner.Scan()
for scanner.Scan() {
beyond5 += scanner.Text() + "\n"
}
Output:
6
7
Playground
I hope it is the solution that you were looking for :-)

Related

Splitting string in 2 parts by removing substring in golang

I'm trying to parse strings that look something like this:
abc***********xyz
into a slice (or 2 variables) of "abc" and "xyz", removing all the asterisks.
The number of * can be variable and so can the letters on each side, so it's not necessarily a fixed length. I'm wondering if go has a nice way of doing this with the strings package?
Use strings.FieldsFunc where * is a field separator.
s := "abc***********xyz"
z := strings.FieldsFunc(s, func(r rune) bool { return r == '*' })
fmt.Println(len(z), z) // prints 2 [abc xyz]
Live Example.
Split on any number of asterisks:
words := regexp.MustCompile(`\*+`).Split(str, -1)
See live demo.
For best performance, write a for loop:
func SplitAsteriks(s string) []string {
var (
in bool // true if inside a token
tokens []string // collect function result here
i int
)
for j, r := range s {
if r == '*' {
if in {
// transition from token to separator
tokens = append(tokens, s[i:j])
in = false
}
} else {
if !in {
// transition from one or more separators to token
i = j
in = true
}
}
}
if in {
tokens = append(tokens, s[i:])
}
return tokens
}
Playground.
if performance is an issue, you can use this func:
func SplitAsteriks(s string) (result []string) {
if len(s) == 0 {
return
}
i1, i2 := 0, 0
for i := 0; i < len(s); i++ {
if s[i] == '*' && i1 == 0 {
i1 = i
}
if s[len(s)-i-1] == '*' && i2 == 0 {
i2 = len(s) - i
}
if i1 > 0 && i2 > 0 {
result = append(result, s[:i1], s[i2:])
return
}
}
result = append(result, s)
return
}
playground
Use this code given that the string is specified to have two parts:
s := "abc***********xyz"
p := s[:strings.IndexByte(s, '*')]
q := s[strings.LastIndexByte(s, '*')+1:]
fmt.Println(p, q) // prints abc xyz

How to split string two between characters

I want to split a string up between two characters( {{ and }} ).
I have an string like {{number1}} + {{number2}} > {{number3}}
and I'm looking for something that returns:
[number1, number2, number3]
You can try it with Regex:
s := "{{number1}} + {{number2}} > {{number3}}"
// Find all substrings in form {<var name>}
re := regexp.MustCompile("{[a-z]*[0-9]*[a-z]*}")
nums := re.FindAllString(s, -1)
// Remove '{' and '}' from all substrings
for i, _ := range nums {
nums[i] = strings.TrimPrefix(nums[i], "{")
nums[i] = strings.TrimSuffix(nums[i], "}")
}
fmt.Println(nums) // output: [number1 number2 number3]
You can experiment with regex here: https://regex101.com/r/kkPWAS/1
Use the regex [A-Za-z]+[0-9] and filter the alpha numeric parts of the string as string array.
package main
import (
"fmt"
"regexp"
)
func main() {
s := `{{number1}} + {{number2}} > {{number3}}`
re := regexp.MustCompile("[A-Za-z]+[0-9]")
p := re.FindAllString(s, -1)
fmt.Println(p) //[number1 number2 number3]
}
the hard way using the template parser ^^
package main
import (
"fmt"
"strings"
"text/template/parse"
)
func main() {
input := "{{number1}} + {{number2}} > {{number3}}"
out := parseit(input)
fmt.Printf("%#v\n", out)
}
func parseit(input string) (out []string) {
input = strings.Replace(input, "{{", "{{.", -1) // Force func calls to become variables.
tree, err := parse.Parse("", input, "{{", "}}")
if err != nil {
panic(err)
}
visit(tree[""].Root, func(n parse.Node) bool {
x, ok := n.(*parse.FieldNode)
if ok {
out = append(out, strings.Join(x.Ident, "."))
}
return true
})
return
}
func visit(n parse.Node, fn func(parse.Node) bool) bool {
if n == nil {
return true
}
if !fn(n) {
return false
}
if l, ok := n.(*parse.ListNode); ok {
for _, nn := range l.Nodes {
if !visit(nn, fn) {
continue
}
}
}
if l, ok := n.(*parse.RangeNode); ok {
if !visit(l.BranchNode.Pipe, fn) {
return false
}
if l.BranchNode.List != nil {
if !visit(l.BranchNode.List, fn) {
return false
}
}
if l.BranchNode.ElseList != nil {
if !visit(l.BranchNode.ElseList, fn) {
return false
}
}
}
if l, ok := n.(*parse.ActionNode); ok {
for _, c := range l.Pipe.Decl {
if !visit(c, fn) {
continue
}
}
for _, c := range l.Pipe.Cmds {
if !visit(c, fn) {
continue
}
}
}
if l, ok := n.(*parse.CommandNode); ok {
for _, a := range l.Args {
if !visit(a, fn) {
continue
}
}
}
if l, ok := n.(*parse.PipeNode); ok {
for _, a := range l.Decl {
if !visit(a, fn) {
continue
}
}
for _, a := range l.Cmds {
if !visit(a, fn) {
continue
}
}
}
return true
}
If it happens you really were manipulating template string, but fails to do so due to function calls and that you do not want to execute this input = strings.Replace(input, "{{", "{{.", -1) // Force func calls to become variables.
You can always force load a template using functions similar to
var reMissingIdent = regexp.MustCompile(`template: :[0-9]+: function "([^"]+)" not defined`)
func ParseTextTemplateAnyway(s string) (*texttemplate.Template, texttemplate.FuncMap, error) {
fn := texttemplate.FuncMap{}
for {
t, err := texttemplate.New("").Funcs(fn).Parse(s)
if err == nil {
return t, fn, err
}
s := err.Error()
res := reMissingIdent.FindAllStringSubmatch(s, -1)
if len(res) > 0 {
fn[res[0][1]] = func(s ...interface{}) string { return "" }
} else {
return t, fn, err
}
}
// return nil, nil
}
You don't need to use libraries. You can create your own function.
package main
const r1 = '{'
const r2 = '}'
func GetStrings(in string) (out []string) {
var tren string
wr := false
f := true
for _, c := range in {
if wr && c != r2 {
tren = tren + string(c)
}
if c == r1 {
f = !f
wr = f
}
if c == r2 {
wr = false
if f {
out = append(out, tren)
tren = ""
}
f = !f
}
}
return
}

GoLang Get String at Line N in Byte Slice

In a personal project I am implementing a function that returns a random line from a long file. For it to work I have to create a function that returns a string at line N, a second function that creates a random number between 0 and lines in file. While I was implementing those I figured it may be more efficient to store the data in byte slices by default, rather than storing them in separate files, which have to be read at run time.
Question: How would I go about implementing a function that returns a string at a random line of the []byte representation of my file.
My function for getting a string from a file:
func atLine(n int) (s string) {
f, err := os.Open("./path/to/file")
if err != nil {
panic("Could not read file.")
}
defer f.Close()
r := bufio.NewReader(f)
for i := 1; ; i++ {
line, _, err := r.ReadLine()
if err != nil {
break
}
if i == n {
s = string(line[:])
break
}
}
return s
}
Additional info:
Lines are not longer than 50 characters at most
Lines have no special characters (although a solution handling those is welcome)
Number of lines in the files is known and so the same can be applied for []byte
Dealing with just the question part (and not the sanity of this) - you have a []byte and want to get a specific string line from it - the bytes.Reader has no ReadLine method which you will have already noticed.
You can pass a bytes reader to bufio.NewReader, and gain the ReadLine functionality you are trying to access.
bytesReader := bytes.NewReader([]byte("test1\ntest2\ntest3\n"))
bufReader := bufio.NewReader(bytesReader)
value1, _, _ := bufReader.ReadLine()
value2, _, _ := bufReader.ReadLine()
value3, _, _ := bufReader.ReadLine()
fmt.Println(string(value1))
fmt.Println(string(value2))
fmt.Println(string(value3))
Obviously it is not sensible to ignore the errors, but for the purpose of brevity I do it here.
https://play.golang.org/p/fRQUfmZQke
Results:
test1
test2
test3
From here, it is straight forward to fit back into your existing code.
Here is an example of fast (in the order of nanoseconds) random access to lines of text as byte data. The data is buffered and indexed in memory.
lines.go:
package main
import (
"bytes"
"fmt"
"io/ioutil"
"os"
)
type Lines struct {
data []byte
index []int // line start, end pairs for data[start:end]
}
func NewLines(data []byte, nLines int) *Lines {
bom := []byte{0xEF, 0xBB, 0xBF}
if bytes.HasPrefix(data, bom) {
data = data[len(bom):]
}
lines := Lines{data: data, index: make([]int, 0, 2*nLines)}
for i := 0; ; {
j := bytes.IndexByte(lines.data[i:], '\n')
if j < 0 {
if len(lines.data[i:]) > 0 {
lines.index = append(lines.index, i)
lines.index = append(lines.index, len(lines.data))
}
break
}
lines.index = append(lines.index, i)
j += i
i = j + 1
if j > 0 && lines.data[j-1] == '\r' {
j--
}
lines.index = append(lines.index, j)
}
if len(lines.index) != cap(lines.index) {
lines.index = append([]int(nil), lines.index...)
}
return &lines
}
func (l *Lines) N() int {
return len(l.index) / 2
}
func (l *Lines) At(n int) (string, error) {
if 1 > n || n > l.N() {
err := fmt.Errorf(
"data has %d lines: at %d out of range",
l.N(), n,
)
return "", err
}
m := 2 * (n - 1)
return string(l.data[l.index[m]:l.index[m+1]]), nil
}
var (
// The Complete Works of William Shakespeare
// http://www.gutenberg.org/cache/epub/100/pg100.txt
fName = `/home/peter/shakespeare.pg100.txt`
nLines = 124787
)
func main() {
data, err := ioutil.ReadFile(fName)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
lines := NewLines(data, nLines)
for _, at := range []int{1 - 1, 1, 2, 12, 42, 124754, lines.N(), lines.N() + 1} {
line, err := lines.At(at)
if err != nil {
fmt.Fprintf(os.Stderr, "%d\t%v\n", at, err)
continue
}
fmt.Printf("%d\t%q\n", at, line)
}
}
Output:
0 data has 124787 lines: at 0 out of range
1 "The Project Gutenberg EBook of The Complete Works of William Shakespeare, by"
2 "William Shakespeare"
12 "Title: The Complete Works of William Shakespeare"
42 "SHAKESPEARE IS COPYRIGHT 1990-1993 BY WORLD LIBRARY, INC., AND IS"
124754 "http://www.gutenberg.org"
124787 "*** END: FULL LICENSE ***"
124788 data has 124787 lines: at 124788 out of range
lines_test.go:
package main
import (
"io/ioutil"
"math/rand"
"testing"
)
func benchData(b *testing.B) []byte {
data, err := ioutil.ReadFile(fName)
if err != nil {
b.Fatal(err)
}
return data
}
func BenchmarkNewLines(b *testing.B) {
data := benchData(b)
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
lines := NewLines(data, nLines)
_ = lines
}
}
func BenchmarkLineAt(b *testing.B) {
data := benchData(b)
lines := NewLines(data, nLines)
ats := make([]int, 4*1024)
ats[0], ats[1] = 1, lines.N()
rand.Seed(42)
for i := range ats[2:] {
ats[2+i] = 1 + rand.Intn(lines.N())
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
at := ats[i%len(ats)]
line, err := lines.At(at)
if err != nil {
b.Error(err)
}
_ = line
}
}
Output
$ go test -bench=. lines.go lines_test.go
BenchmarkNewLines-8 1000 1898347 ns/op 1998898 B/op 2 allocs/op
BenchmarkLineAt-8 50000000 45.1 ns/op 49 B/op 0 allocs/op

Reading from reader until a string is reached

I am trying to write a function to keep reading from a buffered reader until I hit a certain string, then to stop reading and return everything read prior to that string.
In other words, I want to do the same thing as reader.ReadString() does, except taking a string instead of a single byte.
For instance:
mydata, err := reader.ReadString("\r\n.\r\n") //obviously will not compile
How can I do this?
Thanks in advance,
Twichy
Amendment 1: Previous attempt
Here is my previous attempt; its badly written and doesnt work but hopefully it demonstrates what I am trying to do.
func readDotData(reader *bufio.Reader)(string, error){
delims := []byte{ '\r', '\n', '.', '\r', '\n'}
curpos := 0
var buffer []byte
for {
curpos = 0
data, err := reader.ReadSlice(delims[0])
if err!=nil{ return "", err }
buffer = append(buffer, data...)
for {
curpos++
b, err := reader.ReadByte()
if err!=nil{ return "", err }
if b!=delims[curpos]{
for curpos >= 0{
buffer = append(buffer, delims[curpos])
curpos--
}
break
}
if curpos == len(delims){
return string(buffer[len(buffer)-1:]), nil
}
}
}
panic("unreachable")
}
package main
import (
"bytes"
"fmt"
"log"
)
type reader interface {
ReadString(delim byte) (line string, err error)
}
func read(r reader, delim []byte) (line []byte, err error) {
for {
s := ""
s, err = r.ReadString(delim[len(delim)-1])
if err != nil {
return
}
line = append(line, []byte(s)...)
if bytes.HasSuffix(line, delim) {
return line[:len(line)-len(delim)], nil
}
}
}
func main() {
src := bytes.NewBufferString("123deli456elim789delimABCdelimDEF")
for {
b, err := read(src, []byte("delim"))
if err != nil {
log.Fatal(err)
}
fmt.Printf("%q\n", b)
}
}
Playground
Output:
"123deli456elim789"
"ABC"
2009/11/10 23:00:00 EOF
http://play.golang.org/p/BpA5pOc-Rn
package main
import (
"bytes"
"fmt"
)
func main() {
b := bytes.NewBuffer([]byte("Hello, playground!\r\n.\r\nIrrelevant trailer."))
c := make([]byte, 0, b.Len())
for {
p := b.Bytes()
if bytes.Equal(p[:5], []byte("\r\n.\r\n")) {
fmt.Println(string(c))
return
}
c = append(c, b.Next(1)...)
}
}
For example,
package main
import (
"bufio"
"bytes"
"fmt"
"strings"
)
var delim = []byte{'\r', '\n', '.', '\r', '\n'}
func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
for i := 0; i+len(delim) <= len(data); {
j := i + bytes.IndexByte(data[i:], delim[0])
if j < i {
break
}
if bytes.Equal(data[j+1:j+len(delim)], delim[1:]) {
// We have a full delim-terminated line.
return j + len(delim), data[0:j], nil
}
i = j + 1
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func main() {
delims := string(delim)
input := "1234" + delims + "5678" + delims + "1234567901234567890" + delims
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(ScanLines)
for scanner.Scan() {
fmt.Printf("%s\n", scanner.Text())
}
if err := scanner.Err(); err != nil {
fmt.Printf("Invalid input: %s", err)
}
}
Output:
1234
5678
1234567901234567890
Because you have the same byte in the string, you can do it as below:
func readWithEnd(reader *bufio.Reader) ([]byte, error) {
message, err := reader.ReadBytes('#')
if err != nil {
return nil, err
}
a1, err := reader.ReadByte()
if err != nil {
return nil, err
}
message = append(message, a1)
if a1 != '\t' {
message2, err := readWithEnd(reader)
if err != nil {
return nil, err
}
ret := append(message, message2...)
return ret, nil
}
a2, err := reader.ReadByte()
if err != nil {
return nil, err
}
message = append(message, a2)
if a2 != '#' {
message2, err := readWithEnd(reader)
if err != nil {
return nil, err
}
ret := append(message, message2...)
return ret, nil
}
return message, nil
}
This is the sample that can recognize the "#\t#" in TCP connection

Using a Goroutine actually takes longer to execute

I'm sure that I'm doing something wrong, I have a Go program that parses in 3D models in OBJ format and outputs a json object. When I run it without adding in goroutines I get the following output:
$ go run objParser.go ak47.obj extincteur_obj.obj
--Creating ak47.json3d from ak47.obj
--Exported 85772 faces with 89088 verticies
--Creating extincteur_obj.json3d from extincteur_obj.obj
--Exported 150316 faces with 151425 verticies
Parsed 2 files in 8.4963s
Then I added in the goroutines and I get this output:
$ go run objParser.go ak47.obj extincteur_obj.obj
--Creating ak47.json3d from ak47.obj
--Creating extincteur_obj.json3d from extincteur_obj.obj
--Exported 85772 faces with 89088 verticies
--Exported 150316 faces with 151425 verticies
Parsed 2 files in 10.23137s
The order of how it's printed is what I expected given the interlacing of the parsing but I have no idea why it actually takes longer! The code is pretty long, I snipped what I could but it's still pretty long, sorry about that!
package main
func parseFile(name string, finished chan int) {
var Verts []*Vertex
var Texs []*TexCoord
var Faces []*Face
var objFile, mtlFile, jsonFile *os.File
var parseMaterial bool
// Set up files and i/o
inName := name
outName := strings.Replace(inName, ".obj", ".json3d", -1)
parseMaterial = false
fmt.Printf("--"+FgGreen+"Creating"+Reset+" %s from %s\n", outName, inName)
var err error
var part []byte
var prefix bool
if objFile, err = os.Open(inName); err != nil {
fmt.Println(FgRed+"!!Failed to open input file!!"+Reset)
return
}
if jsonFile, err = os.Create(outName); err != nil {
fmt.Println(FgRed+"!!Failed to create output file!!"+Reset)
return
}
reader := bufio.NewReader(objFile)
writer := bufio.NewWriter(jsonFile)
buffer := bytes.NewBuffer(make([]byte, 1024))
// Read the file in and parse out what we need
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
line := buffer.String()
if(strings.Contains(line, "v ")) {
Verts = append(Verts, parseVertex(line))
} else if(strings.Contains(line, "vt ")) {
Texs = append(Texs, parseTexCoord(line))
} else if(strings.Contains(line, "f ")) {
Faces = append(Faces, parseFace(line, Verts, Texs))
} else if(strings.Contains(line, "mtllib ")) {
mtlName := strings.Split(line, " ")[1]
if mtlFile, err = os.Open(mtlName); err != nil {
fmt.Printf("--"+FgRed+"Failed to find material file: %s\n"+Reset, mtlName)
parseMaterial = false
} else {
parseMaterial = true
}
}
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
objFile.Close()
// Write out the data
writer.WriteString("{\"obj\":[\n");
// Write out the verts
writer.WriteString("{\"vrt\":[\n");
for i, vert := range Verts {
writer.WriteString(vert.String())
if i < len(Verts) - 1 { writer.WriteString(",") }
writer.WriteString("\n")
}
// Write out the faces
writer.WriteString("],\"fac\":[\n")
for i, face := range Faces {
writer.WriteString(face.String(true))
if i < len(Faces) - 1 { writer.WriteString(",") }
writer.WriteString("\n")
}
// Write out the normals
writer.WriteString("],\"nrm\":[")
for i, face := range Faces {
writer.WriteString("[")
for j, vert := range face.verts {
length := math.Sqrt((vert.X * vert.X) + (vert.Y * vert.Y) + (vert.Z * vert.Z))
x := vert.X / length
y := vert.Y / length
z := vert.Z / length
normal := fmt.Sprintf("[%f,%f,%f]", x, y, z)
writer.WriteString(normal)
if(j < len(face.verts)-1) { writer.WriteString(",") }
}
writer.WriteString("]")
//writer.WriteString("[0, 1, 0]")
if i < len(Faces) - 1 { writer.WriteString(",") }
writer.WriteString("\n")
}
// Write out the tex coords
writer.WriteString("],\"tex\":[")
for i, face := range Faces {
writer.WriteString("[")
writer.WriteString(face.tex[0].String())
writer.WriteString(",")
writer.WriteString(face.tex[1].String())
writer.WriteString(",")
writer.WriteString(face.tex[2].String())
writer.WriteString("]")
if i < len(Faces) - 1 { writer.WriteString(",") }
writer.WriteString("\n")
}
// Close obj block
writer.WriteString("]}]");
if parseMaterial {
writer.WriteString(",mat:[{");
reader := bufio.NewReader(mtlFile)
// Read the file in and parse out what we need
for {
if part, prefix, err = reader.ReadLine(); err != nil {
break
}
buffer.Write(part)
if !prefix {
line := buffer.String()
if(strings.Contains(line, "map_Kd ")) {
parts := strings.Split(line, " ")
entry := fmt.Sprintf("\"t\":\"%s\",", parts[1])
writer.WriteString(entry)
width, height := 256, 256
var imageFile *os.File
if imageFile, err = os.Open(parts[1]); err != nil {
fmt.Printf("--"+FgRed+"Failed to find %s, defaulting to 256x256"+Reset+"\n", parts[1])
return
} else {
var config image.Config
imageReader := bufio.NewReader(imageFile)
config, err = jpeg.DecodeConfig(imageReader)
width, height = config.Width, config.Height
fmt.Printf("--"+FgGreen+"Verifing"+Reset+" that %s is %dpx x %dpx\n", parts[1], width, height)
}
size := fmt.Sprintf("\"w\":%d,\"h\":%d,", width, height)
writer.WriteString(size)
} else if(strings.Contains(line, "Kd ")) {
parts := strings.Split(line, " ")
entry := fmt.Sprintf("\"r\":%s, \"g\":%s, \"b\":%s,", parts[1], parts[2], parts[3])
writer.WriteString(entry)
}
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
writer.WriteString("\"res\":100,\"uv\":true}]");
}
// Close json
writer.WriteString("}");
writer.Flush()
jsonFile.Close()
fmt.Printf("--"+FgGreen+"Exported"+Reset+" %d faces with %d verticies\n", len(Faces), len(Verts))
finished <- -1
}
func main(){
// Verify we were called correctly
if len(os.Args) < 2 {
fmt.Println("Usage: go run objParser.go <OBJ File>");
return
}
files := len(os.Args)
finished := make(chan int)
now := time.Now()
for i := 1; i < files; i++ {
go parseFile(os.Args[i], finished)
}
for i := 1; i < files; i++ {
<- finished
}
fmt.Printf("Parsed %d files in %s\n", files-1, time.Since(now))
}
You should set GOMAXPROCS environment variable for go to the maximum number of usable processors. Or use function GOMAXPROCS at executing time.

Resources