Pretty new to Go and running into a problem like:
var metrics bytes.Buffer
metrics.WriteString("foo")
metrics.WriteString("
")
metrics.WriteString("bar")
metrics.WriteString("
")
Now I want to cycle through that metrics and split by newline. I tried
for m := strings.Split(metrics.String(), "
") {
log.Printf("metric: %s", m)
}
but I get the following
./relay.go:71: m := strings.Split(metrics.String(), "
") used as value
Considering that strings.Split()
returns an array, it would be easier to use range
m := strings.Split(metrics.String(), "
")
for _, m := range strings.Split(metrics.String(), "
") {
log.Printf("metric: %s", m)
}
Note, to read lines from a string, you can consider "go readline -> string":
bufio.ReadLine()
or better: bufio.Scanner
As in:
const input = "Now is the winter of our discontent,
Made glorious summer by this sun of York.
"
scanner := bufio.NewScanner(strings.NewReader(input))
See more at "Scanner terminating early".
You can do this with a bufio.Scanner
Godoc at http://golang.org/pkg/bufio/#Scanner
Something like this:
var metrics bytes.Buffer
metrics.WriteString("foo")
metrics.WriteString("
")
metrics.WriteString("bar")
metrics.WriteString("
")
scanner := bufio.NewScanner(&metrics)
for scanner.Scan() {
log.Printf("metric: %s", scanner.Text())
}
if err := scanner.Err(); err != nil {
log.Fatal(err)
}
A full example here: http://play.golang.org/p/xrFEGF3h5P