快速实现websocket实时读取文件内容

本文主要是介绍如何模仿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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值