从第一个CRLF(回车换行)读取到末尾的[]byte。

huangapple go评论110阅读模式
英文:

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函数轻松实现,该函数返回一个字节切片中给定子切片的索引:

  1. func afterCRLF(data []byte) []byte {
  2. crlf := []byte("\r\n")
  3. index := bytes.Index(data, crlf)
  4. if index == -1 {
  5. return nil
  6. }
  7. return data[index+len(crlf):]
  8. }

注意:上述函数在返回的字节切片中不包括第一个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:

  1. func afterCRLF(data []byte) []byte {
  2. crlf := []byte("\r\n")
  3. index := bytes.Index(data, crlf)
  4. if index == -1 {
  5. return nil
  6. }
  7. return data[index+len(crlf):]
  8. }

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_

huangapple
  • 本文由 发表于 2015年7月29日 20:32:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/31700489.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定