Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading from reader until a string is reached

Tags:

string

go

I am trying to write a function to keep reading from a buffered reader until I hit a certain string, then to stop reading and return everything read prior to that string.

In other words, I want to do the same thing as reader.ReadString() does, except taking a string instead of a single byte.

For instance:

mydata, err := reader.ReadString("\r\n.\r\n") //obviously will not compile

How can I do this?

Thanks in advance,

Twichy

Amendment 1: Previous attempt

Here is my previous attempt; its badly written and doesnt work but hopefully it demonstrates what I am trying to do.

func readDotData(reader *bufio.Reader)(string, error){
delims := []byte{ '\r', '\n', '.', '\r', '\n'}
curpos := 0
var buffer []byte
for {
    curpos = 0
    data, err := reader.ReadSlice(delims[0])
    if err!=nil{ return "", err }
    buffer = append(buffer, data...)
    for {
        curpos++
        b, err := reader.ReadByte()
        if err!=nil{ return "", err }
        if b!=delims[curpos]{
            for curpos >= 0{
                buffer = append(buffer, delims[curpos])
                curpos--
            }
            break
        }
        if curpos == len(delims){
            return string(buffer[len(buffer)-1:]), nil
        }
    }
}
panic("unreachable")
}
like image 436
64bit_twitchyliquid Avatar asked Jul 29 '13 05:07

64bit_twitchyliquid


2 Answers

package main

import (
        "bytes"
        "fmt"
        "log"
)

type reader interface {
        ReadString(delim byte) (line string, err error)
}

func read(r reader, delim []byte) (line []byte, err error) {
        for {
                s := ""
                s, err = r.ReadString(delim[len(delim)-1])
                if err != nil {
                        return
                }

                line = append(line, []byte(s)...)
                if bytes.HasSuffix(line, delim) {
                        return line[:len(line)-len(delim)], nil
                }
        }
}

func main() {
        src := bytes.NewBufferString("123deli456elim789delimABCdelimDEF")
        for {
                b, err := read(src, []byte("delim"))
                if err != nil {
                        log.Fatal(err)
                }

                fmt.Printf("%q\n", b)
        }
}

Playground


Output:

"123deli456elim789"
"ABC"
2009/11/10 23:00:00 EOF
like image 178
zzzz Avatar answered Sep 30 '22 20:09

zzzz


http://play.golang.org/p/BpA5pOc-Rn

package main

import (
    "bytes"
    "fmt"
)

func main() {
    b := bytes.NewBuffer([]byte("Hello, playground!\r\n.\r\nIrrelevant trailer."))
    c := make([]byte, 0, b.Len())
    for {
        p := b.Bytes()
        if bytes.Equal(p[:5], []byte("\r\n.\r\n")) {
            fmt.Println(string(c))
            return
        }
        c = append(c, b.Next(1)...)

    }
}
like image 35
thwd Avatar answered Sep 30 '22 20:09

thwd