forked from olahol/melody
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
44 lines (35 loc) · 712 Bytes
/
main.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
package main
import (
"github.com/fsnotify/fsnotify"
"github.com/gin-gonic/gin"
"gopkg.in/olahol/melody.v1"
"io/ioutil"
"net/http"
)
func main() {
file := "file.txt"
r := gin.Default()
m := melody.New()
w, _ := fsnotify.NewWatcher()
r.GET("/", func(c *gin.Context) {
http.ServeFile(c.Writer, c.Request, "index.html")
})
r.GET("/ws", func(c *gin.Context) {
m.HandleRequest(c.Writer, c.Request)
})
m.HandleConnect(func(s *melody.Session) {
content, _ := ioutil.ReadFile(file)
s.Write(content)
})
go func() {
for {
ev := <-w.Events
if ev.Op == fsnotify.Write {
content, _ := ioutil.ReadFile(ev.Name)
m.Broadcast(content)
}
}
}()
w.Add(file)
r.Run(":5000")
}