本文主要是介绍如何模仿linux的tail -f,实时读取文件末尾的输出,并展示在web页面中
代码主要是提供一些简单的思路,你可以继续进行一些扩展,包括停止滚动、继续时重新追加等等功能
golang实现,具体代码如下:
编译时需要安装以下依赖:
go get github.com/gorilla/websocket
go get github.com/hpcloud/tail
package main
import (
"flag"
"fmt"
"github.com/gorilla/websocket"
"github.com/hpcloud/tail"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)
/***
编译时需要安装以下依赖:
go get github.com/gorilla/websocket
go get github.com/hpcloud/tail
*/
const (
// Time allowed to write the file to the client.
//writeWait = 1 * time.Second
writeWait = 100 * time.Millisecond
// Time allowed to read the next pong message from the client.
//pongWait = 24 * time.Hour
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Poll file for changes with this period.
filePeriod = 1 * time.Second
)
var (
homeTempl = template.Must(template.New("").Parse(homeHTML))
filename string
addr string
start bool
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
)
func init() {
flag.StringVar(&filename, "f", "/var/log/messages", "指定一个文件的绝对路径")
flag.StringVar(&addr, "a", ":8080", "http 服务地址")
flag.Usage = usage
}
func usage() {
fmt.Fprintf(os.Stderr, `
filewatch v1.0.0:检测文件变化,读取指定的文件,启动一个websocket页面实时读取,类似web版本的tail -f xxxx.log
Usage: filewatch [-f 文件绝对路径] [-a 监听的地址]
example:
filewatch -f /var/log/message -a :8080
`)
flag.PrintDefaults()
}
func readFileIfModified(lastMod time.Time) ([]byte, time.Time, error) {
fi