lundi 29 juin 2015

Go: "tail -f"-like generator

I had this convenient function in Python:

def follow(path):
    with open(self.path) as lines:, 2)  # seek to EOF

        while True:
            line = lines.readline()
            if not line:
                yield line 

It does something similar to UNIX tail -f: you get last lines of a file as they come. It's convenient because you can get the generator without blocking and pass it to another function.

Then I had to do the same thing in Go. I'm new to this language, so I'm not sure whether what I did is idiomatic/correct enough for Go.

Here is the code:

func Follow(fileName string) chan string {

    out_chan := make(chan string)

    file, err := os.Open(fileName)
    if err != nil {

    file.Seek(0, 2)
    bf := bufio.NewReader(file)

    go func() {
        for {
            line, _, err := bf.ReadLine()

            if err == io.EOF {
            } else {
                out_chan <- string(line)

        defer file.Close()

    return out

Is there any cleaner way to do this in Go? I have a feeling that using an asynchronous call for such a thing is an overkill, and it really bothers me.

Aucun commentaire:

Enregistrer un commentaire