/
tail.go
43 lines (40 loc) · 912 Bytes
/
tail.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
package handler
import (
"io"
"net/http"
"github.com/hpcloud/tail"
)
func newTailHandler(hostname, hostPath, tailFile string, whence int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cfg := tail.Config{
Follow: true,
Logger: tail.DiscardingLogger,
Location: &tail.SeekInfo{Offset: 0, Whence: whence},
}
t, err := tail.TailFile(tailFile, cfg)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Add("content-type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
f, _ := w.(http.Flusher)
for {
select {
case <-r.Context().Done():
return
case line, ok := <-t.Lines:
if !ok {
return
}
io.WriteString(w, line.Text+"\n")
if line.Err != nil {
io.WriteString(w, line.Err.Error())
return
}
if f != nil {
f.Flush()
}
}
}
})
}