Reading from reader until a string is reached

go, string

Solution

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)...)

    }
}

Problem

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") } ```

Original source