1. 程式人生 > 其它 >【Go 語言社群】golang的bufio用於內容解析

【Go 語言社群】golang的bufio用於內容解析

golang提供了io.Reader,也就是讀內容,可以從很多地方讀,譬如:

// from string.var r io.Reader = strings.NewReader(string("hello, world"))// from bytes.var r io.Reader = bytes.NewReader([]byte("hello, world!"))// from bytes buffer.var r io.Reader = bytes.NewBuffer([]byte("hello, world"))

這個看起來沒有啥稀奇的,就是從字串或者位元組讀取唄。最後一個bytes.Buffer是寫(Write)時增加到末尾,讀(Read)時從頭開始讀的一個物件,就是個緩衝區。

還有一個比較有用的,帶緩衝區的io:

// buffer readervar r io.Reader = bufio.NewReader(strings.NewReader(string("hello, world")))

這個是和帶緩衝區的寫入是對應的。這個類是給網路reader用的,譬如協議解析,需要看看下面幾個位元組是什麼,然後再解析之類的(Peek)。或者寫入時,不斷將小的bytes寫入,最後Flush之類。

另外,bufio.Reader還提供了特殊的讀法,譬如讀取字串(因為有緩衝區所以能讀得出來)。

// ReadString reads until the first occurrence of delim in the input,
// returning a string containing the data up to and including the delimiter.
// If ReadString encounters an error before finding a delimiter,
// it returns the data read before the error and the error itself (often io.EOF).
// ReadString returns err != nil if and only if the returned data does not end in// delim.
// For simple uses, a Scanner may be more convenient.
func (b *Reader) ReadString(delim byte) (line string, err error) {

對於內容解析,譬如解析下面的json,支援///**/風格的註釋,那麼就可以用scanner,也就是特定格式的掃描提取:

s := bufio.NewScanner(strings.NewReader("/*block comments*///line commentsn{}"))
s.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error){    // read more.
    return 0,nil,nil})for s.Scan() {
    fmt.Println(s.Text())
}
fmt.Println("err is", s.Err())

只需要判斷是否需要的資料是否有滿足,譬如//n是否成對,如果不成對就再讀取。這樣就大大降低了複雜邏輯了。