firstly, the prototype of bufio.ReadString
is
func (b *Reader) ReadString(delim byte) (line string, err error)
it can only take one byte as arg, so your ;
delimiter won't work.
use ;
as delimiter instead.
But if you use ReadString(';')
it will contain other characters in your results, such as '
'
a example:
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
const raw = `select * from table1;
select *
from table2;
select 1;`
br := bufio.NewReader(strings.NewReader(raw))
var err error
var s string
err = nil
for err == nil {
s, err = br.ReadString(';')
if err == nil {
fmt.Printf("%q", s)
}
}
this will get:
"select * from table1;""
select *
from table2;""
select 1;"
online test
Solution:
use Scanner
may be more convenient, and achieve this as bellow.
ps: ;
will be considered as part of words
package main
import (
"bufio"
"fmt"
"os"
"strings"
"bytes"
)
func main() {
const raw = `select * from table1;
select *
from table2;
select 1;`
scanner := bufio.NewScanner(strings.NewReader(raw))
scanner.Split(bufio.ScanWords)
var tmpbuf bytes.Buffer
for scanner.Scan() {
w := scanner.Text()
tmpbuf.WriteString(w)
if w[len(w)-1] == ';' {
tmpbuf.WriteString("
")
fmt.Printf(tmpbuf.String())
tmpbuf.Reset()
} else {
tmpbuf.WriteString(" ")
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
}
you will get:
select * from table1;
select * from table2;
select 1;
online test