This code is a reference to the Mu class network video tutorials, mainly f.Seek (0, os.SEEK_END) moved to the end, but there is a small problem, when the file is re-opened to empty the contents emptied, it is no longer not to read the data, such as the open reading echo ''> 1.log this will never be read, tail package is to solve this problem
package main import ( "bufio" "fmt" "io" "os" "strings" "time" ) func main() { readChannel := make(chan string) go readFile(readChannel) for r := range readChannel { fmt.Println(r) } } func readFile(readChannel chan string) { f, err := os.Open("1.txt") if err != nil { panic(fmt.Sprintf("open file error:%s", err.Error())) } //移动到文件末尾 f.Seek(0, os.SEEK_END) reader := bufio.NewReader(f) for { line, err := reader.ReadBytes('\n') fmt.Println(err) if err == io.EOF { time.Sleep(time.Second) continue } else if err != nil { panic("ReadBytes error:" + err.Error()) } lineStr := strings.TrimSpace(string(line)) readChannel <- lineStr } }
When using tail bag test, have re-open the file