首頁 > 後端開發 > Golang > 主體

如何使用 Go 中的自訂 SplitFunc 從緩衝區讀取資料直到特定分隔符號 CRLF?

Patricia Arquette
發布: 2024-10-26 09:48:03
原創
696 人瀏覽過

How to read data from a buffer until a specific delimiter, CRLF, using a custom SplitFunc in Go?

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

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!