使用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中文網其他相關文章!