Home > Backend Development > Golang > How to Read Multiline Responses with CR/LF Delimiter in Go?

How to Read Multiline Responses with CR/LF Delimiter in Go?

Susan Sarandon
Release: 2024-10-28 16:48:02
Original
645 people have browsed it

How to Read Multiline Responses with CR/LF Delimiter in Go?

Reading Multiline Responses with CR/LF Delimiter in Go

When implementing a Beanstalkd client in Go, it's necessary to read multiline responses that are delimited by both the newline character (n) and the carriage return character (r). The default function bufio.ReadLine only supports delimiting by n.

Reading Until CRLF

To read until the CRLF delimiter, you can use bufio.Scanner with a custom SplitFunc function:

<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>
Copy after login

In this case, dropCR removes the trailing 'r' character from the token.

You can then use a bufio.Scanner with the ScanCRLF function to read the data:

<code class="go">scanner := bufio.NewScanner(this.reader)
scanner.Split(ScanCRLF)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}</code>
Copy after login

Alternatively, bufio.NewReaderSize can be used to read a specific length:

<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>
Copy after login

The above is the detailed content of How to Read Multiline Responses with CR/LF Delimiter in Go?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template