[go] go wait to read the data content of the last line


This code is based on the video tutorial of MOOC, mainly F. seek (0, os.SEEK_ End) is moved to the end, but there is a small problem. When the open file is emptied again and the content is emptied, the data can no longer be read. For example, when the echo ” > 1.log is opened for reading, the data can no longer be read. The tail package solves this problem

package main

import (

func main() {
    readChannel := make(chan string)
    go readFile(readChannel)
    for r := range readChannel {
func readFile(readChannel chan string) {
    f, err := os.Open("1.txt")
    if err != nil {
        panic(fmt.Sprintf("open file error:%s", err.Error()))
    //Move to the end of the file
    f.Seek(0, os.SEEK_END)
    reader := bufio.NewReader(f)
    for {
        line, err := reader.ReadBytes('\n')
        if err == io.EOF {
        } else if err != nil {
            panic("ReadBytes error:" + err.Error())

        lineStr := strings.TrimSpace(string(line))

When using tail package test, there are re open files