-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtailHandlers.go
82 lines (64 loc) · 1.72 KB
/
tailHandlers.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
74
75
76
77
78
79
80
81
82
package main
import (
"encoding/json"
"fmt"
"github.com/hpcloud/tail"
"log"
"net/http"
"sync"
)
func createStartTailHandler(broadcast *chan *message, usePolling *bool, tailers *map[string]*tail.Tail, tailMux *sync.Mutex) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var fileIdent fileIdentifier
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&fileIdent)
if err != nil || fileIdent.FilePath == "" || (*tailers)[fileIdent.FilePath] != nil {
w.WriteHeader(500)
return
}
fileTail, err := tail.TailFile(fileIdent.FilePath, tail.Config{Follow: true, Poll: *usePolling})
if err != nil {
log.Println(err)
w.WriteHeader(500)
return
}
tailMux.Lock()
(*tailers)[fileIdent.FilePath] = fileTail
tailMux.Unlock()
go handleNewLines(&fileTail.Lines, broadcast, fileIdent.FilePath)
}
}
func handleNewLines(lines *chan *tail.Line, broadcast *chan *message, filePath string) {
for line := range *lines {
txt := line.Text
msg := newMessageWithFileName(txt, filePath)
*broadcast <- msg
fmt.Println(txt)
}
}
func createStopTailHandler(tailers *map[string]*tail.Tail, tailMux *sync.Mutex) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var fileIdent fileIdentifier
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&fileIdent)
if err != nil {
w.WriteHeader(500)
fmt.Println(err)
fmt.Println("error when deleting")
return
}
if fileIdent.FilePath == "" {
w.WriteHeader(500)
fmt.Println("filepath empty")
return
}
if (*tailers)[fileIdent.FilePath] == nil {
w.WriteHeader(500)
fmt.Println("filepath nil")
return
}
tailMux.Lock()
delete(*tailers, fileIdent.FilePath)
tailMux.Unlock()
}
}