在Go 中實作Beanstalkd 客戶端時,需要讀取由換行符分隔的多行響應(n) 和回車符(r)。預設函數 bufio.ReadLine 僅支援 n 分隔。
要讀取直到CRLF 分隔符,您可以將bufio.Scanner 與自訂SplitFunc 函數結合使用:
<code class="go">import ( "bufio" "fmt" "io" "bytes" ) 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 }</code>
在這種情況下,dropCR 會從令牌中刪除尾隨的「r」字元。
然後您可以使用帶有 ScanCRLF 函數的 bufio.Scanner 來讀取資料:
<code class="go">scanner := bufio.NewScanner(this.reader) scanner.Split(ScanCRLF) for scanner.Scan() { fmt.Println(scanner.Text()) }</code>
或者,bufio.NewReaderSize 可用於讀取特定長度:
<code class="go">var nr_of_bytes int nr_of_bytes, _ = strconv.Atoi(res) buf := make([]byte, nr_of_bytes) _, _ = io.ReadAtLeast(this.reader,buf, nr_of_bytes)</code>
以上是如何在 Go 中使用 CR/LF 分隔符號讀取多行回應?的詳細內容。更多資訊請關注PHP中文網其他相關文章!