-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathwebtail.go
73 lines (62 loc) · 1.2 KB
/
webtail.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"bufio"
"flag"
"html/template"
"io"
"net/http"
"os"
"time"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
var (
stdIn bool
filePath string
addr = flag.String("addr", ":8081", "http service address")
)
func writer(ws *websocket.Conn) {
defer ws.Close()
var r *bufio.Reader
if stdIn {
r = bufio.NewReader(os.Stdin)
} else {
f, _ := os.Open(filePath)
r = bufio.NewReader(f)
defer f.Close()
}
for {
p, err := r.ReadBytes('\n')
if err != io.EOF {
ws.WriteMessage(websocket.TextMessage, p)
}
time.Sleep(2 * time.Second)
}
}
func serveHome(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
t, _ := template.ParseFiles("webtail.html")
var v = struct {
Host string
}{
r.Host,
}
t.Execute(w, &v)
}
func serveWs(w http.ResponseWriter, r *http.Request) {
ws, _ := upgrader.Upgrade(w, r, nil)
go writer(ws)
}
func main() {
flag.Parse()
if flag.NArg() < 1 {
stdIn = true
} else {
filePath = flag.Args()[0]
}
http.HandleFunc("/", serveHome)
http.HandleFunc("/ws", serveWs)
http.ListenAndServe(*addr, nil)
}