golang的bufio用于内容解析
来源:互联网 发布:软件搬家 编辑:程序博客网 时间:2024/06/06 02:43
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 comments\n{}"))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
是否成对,如果不成对就再读取。这样就大大降低了复杂逻辑了。
具体实现,参考:go-oryx
0 0
- golang的bufio用于内容解析
- golang 中bufio包的用法
- golang 中bufio包的用法
- golang 中bufio包的用法
- Golang bufio包使用范例
- golang的xml解析
- Xilinx 7 Series FPGA时钟网络的区别(BUFG,BUFGR,BUFIO)以及ISE实现流程软件工作内容
- golang基础-终端读(Scanln\bufio)、bufio文件读、、ioutil读读压缩、缓冲区读写、文件写入、文件拷贝
- go学习笔记之bufio的使用
- Golang ReverseProxy 简单的反向代理用于内网穿透
- 用于显示多极联动菜单的内容
- 用于抓取网页内容的常用正则
- 准备用于工作的学习内容
- 在已知XML文件内容时,使用dom4j简单解析XML(String类型的XML)(用于服务器端)
- golang sql连接池的实现解析
- golang解析xml namespace prefix的bug
- 一个用于解析xml文档的类
- Flex解析URL用于RO的EndPoint
- 独立日记 2016年1月3日 day13
- 大数据系列第二课:scala基础
- 新年本应新气象
- Exception in thread "http-bio-8080-exec-7"内存溢出问题
- C#——winform下的小例子
- golang的bufio用于内容解析
- c语言中的布尔类型
- android 图片操作之BitmapMesh
- 航电2010水仙花数
- BMP文件结构解析
- CentOS 7中 安装nginx服务器
- 个人笔记之style
- [codeforces]Goodbye_2015
- Windows 2008设置域用户帐户密码策略