ホームページ  >  記事  >  バックエンド開発  >  Go のカスタム SplitFunc を使用して、特定の区切り文字 CRLF までバッファからデータを読み取る方法は?

Go のカスタム SplitFunc を使用して、特定の区切り文字 CRLF までバッファからデータを読み取る方法は?

Patricia Arquette
Patricia Arquetteオリジナル
2024-10-26 09:48:03697ブラウズ

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。