英文:
read a []byte from first CRLF till the end
问题
在Go语言中,如果有一个[]byte
(通过ioutil.ReadAll
获得),我应该从第一个换行符CRLF(回车换行)读取直到块的末尾。
你能给我一些示例吗?
英文:
in golang, having a []byte
(resulting from ioutil.ReadAll
), i should need to read from the first newline CRLF until the end of the block.
could you point me some examples?
答案1
得分: 2
这可以通过使用bytes.Index
函数轻松实现,该函数返回一个字节切片中给定子切片的索引:
func afterCRLF(data []byte) []byte {
crlf := []byte("\r\n")
index := bytes.Index(data, crlf)
if index == -1 {
return nil
}
return data[index+len(crlf):]
}
注意:上述函数在返回的字节切片中不包括第一个CRLF。如果需要包括这两个字符,请删除+len(crlf)
。
示例:https://play.golang.org/p/WdylrkPwU_
英文:
This is can be done easily using the bytes.Index
function, which returns the index of a given sub-slice of bytes in another byte slice:
func afterCRLF(data []byte) []byte {
crlf := []byte("\r\n")
index := bytes.Index(data, crlf)
if index == -1 {
return nil
}
return data[index+len(crlf):]
}
Note: the above function does not include the first CRLF in the returned byte slice. Remove +len(crlf)
if you need those two characters included.
Example: https://play.golang.org/p/WdylrkPwU_
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论