首页 > 后端开发 > Golang > 正文

如何使用 Go 中的自定义 SplitFunc 从缓冲区读取数据直到特定分隔符 CRLF?

Patricia Arquette
发布: 2024-10-26 09:48:03
原创
696 人浏览过

How to read data from a buffer until a specific delimiter, CRLF, using a custom SplitFunc in Go?

使用 CRLF 的自定义分隔读取器

从缓冲区读取数据,直到达到特定分隔符,在本例中为 CRLF(回车符、换行)序列,为 bufio.Scanner 实现自定义 SplitFunc。

<code class="go">// ScanCRLF splits the input data into tokens that are terminated by CRLF.
func ScanCRLF(data []byte, atEOF bool) (advance int, token []byte, err error) {
    if atEOF && len(data) == 0 {
        return 0, nil, nil
    }
    if i := bytes.Index(data, []byte{'\r', '\n'}); i >= 0 {
        return i + 2, dropCR(data[0:i]), nil
    }
    if atEOF {
        return len(data), dropCR(data), nil
    }
    return 0, nil, nil
}

// dropCR drops a terminal \r from the data.
func dropCR(data []byte) []byte {
    if len(data) > 0 && data[len(data)-1] == '\r' {
        return data[0 : len(data)-1]
    }
    return data
}</code>
登录后复制

使用自定义扫描仪包裹阅读器并使用 Scan() 函数读取每一行:

<code class="go">// Wrap the reader with the custom scanner
scanner := bufio.NewScanner(this.reader)
scanner.Split(ScanCRLF)

// Read each line using the scanner
for scanner.Scan() {
    // Process the line as needed...
}

// Check for any errors encountered by the scanner
if err := scanner.Err(); err != nil {
    // Log or handle the error
}</code>
登录后复制

替代方案:读取特定数量的字节

另一种选择是读取特定数量的字节。首先,您需要使用协议确定正文的大小,例如,通过从响应中读取“字节”值。

<code class="go">// Read the expected number of bytes
nr_of_bytes, err := this.reader.ReadNumberBytesSomeHow()
if err != nil {
    // Handle the error
}

// Allocate a buffer to hold the body
buf := make([]byte, nr_of_bytes)

// Read the body into the buffer
this.reader.Read(buf)

// Process the body as needed...</code>
登录后复制

但是,依赖字节计数器可能存在风险。建议使用带有 CRLF 分隔符的自定义读取器方法,因为它更严格地遵循协议。

以上是如何使用 Go 中的自定义 SplitFunc 从缓冲区读取数据直到特定分隔符 CRLF?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!