How do I read up to a pair of values?

Issue

So I have a function that reads values from a TCP connection. I want to read the line until a delimiter ‘\b\r’. So far I have

func func1(someconnection net.Conn) string {
    c := bufio.NewReader(someconnection)
    buff1 := make([]byte, predefinedsizeofmessage)
    buff1, err := c.ReadBytes(byte('\r'))

    if err != nil {
        fmt.Printf("Connection closed")
    }

    message:= strings.Trim(string(buff1), delimiter)

    if len(message) == predefinedsizeofmessage {
        fmt.Printf("The message is in the wrong format")
    }

    fmt.Printf("The messageis: %s\n", message)

    return message
}

This is clearly problematic in case I read a \r before the delimiter. I’ve seen examples of the use of Scanners which I’ve tried but for some reason, the client calls a timeout when they are used. Perhaps, I implemented the Scanner improperly.

Solution

The bufio.Reader only supports single byte delimiters, you should use a bufio.Scanner with a custom split function to split on multi-byte delimiters.

Perhaps a modified version of https://stackoverflow.com/a/37531472/1205448

Answered By – Dylan Reimerink

Answer Checked By – Mary Flores (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.