我正在使用 Scan
从 IMAP 连接一次扫描第 1 行,这些行应该以 \r\n
结尾,但我怀疑其中的一些我得到的行实际上只是以 \n
结尾,因为在特定实例中解析主体原子时我得到的数据量不正确
(* 8620 FETCH (BODY[] {7060}
是我在这封电子邮件中得到的正文,但如果将换行符计算为 2,这似乎比计数长字节)
// ...
r := bufio.NewScanner(d.conn)
for r.Scan() {
line := r.Text()
len(line) // gets the line length WITHOUT the newline
}
有什么方法可以用换行符来获取长度吗?或者获取扫描仪停止时使用的 token 的长度?
最佳答案
虽然这是一个答案,从字面意义上回答了我关于包含 \n
和潜在的 \r
的问题,但首先在阅读IMAP 服务器的响应不是正确的工具,我将重写我对扫描器的使用并将其替换为 bufio.Reader。
您可以指定在您的扫描器中使用的自定义拆分函数,例如,您可以将 ScanLines 拆分函数移植到一个不会使用返回的 token 丢弃换行符的函数。
// ...
r := bufio.NewScanner(d.conn)
r.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\n'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, data[0 : i+1], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
})
for r.Scan() {
line := r.Text()
len(line) // now gets the line length WITH the newline
}
关于go - 使用扫描仪时如何获取包括换行符在内的行长?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53264958/