>  기사  >  백엔드 개발  >  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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.