This is a creation in Article, where the information may have evolved or changed.
The Golang provides IO. Reader, which reads content, can be read from many places, such as:
// 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"))
This does not seem to be unusual, is to read from a string or byte. One last bytes. Buffer is an object that is added to the end when writing (write), read (read), and reads from the beginning.
There is also a more useful IO with buffers:
// buffer readervar r io.Reader = bufio.NewReader(strings.NewReader(string("hello, world")))
This is corresponding to a write with a buffer. This class is for network reader, such as protocol parsing, need to see what the following bytes are, and then parse the like (Peek). Or write, keep the small bytes written, and finally flush.
In addition, Bufio. Reader also provides special reading methods, such as reading a string (which can be read because it has a buffer).
ReadString ReadsuntilThe first occurrence of DeliminchThe input,//returning astringcontaining the data up to andIncluding the delimiter.//If ReadString encounters anErrorBefore finding a delimiter,//it returns the data read before theError andTheErroritself (oftenio. EOF).//ReadString returns ERR! =Nil if andOnlyifThe returned data does not End inchdelim.//for simple uses, a Scanner is more Convenient.func (b *reader) ReadString (delim bytes) (linestringErrError) {
For content parsing, such as parsing the following JSON, support, //
and /**/
style annotations, you can use scanner, which is a specific format of the scan extraction:
s := bufio.NewScanner(strings.NewReader("/*block comments*///line comments\n{}"))s.Split(func(data []byteboolint, token []byte, err error){ // read more. return 0,nil,nil})for s.Scan() { fmt.Println(s.Text())}fmt.Println("err is", s.Err())
It is only necessary to determine whether the required data is satisfied, such as whether //
\n
it is paired, and then read if it is not. This greatly reduces the complexity of the logic.
Concrete implementation, reference: Go-oryx