forked from InkProject/ink
/
serve.go
87 lines (76 loc) · 1.82 KB
/
serve.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
83
84
85
86
87
package main
import (
"fmt"
"github.com/InkProject/ink.go"
"github.com/go-fsnotify/fsnotify"
"github.com/gorilla/websocket"
"github.com/facebookgo/symwalk"
"os"
"path/filepath"
)
var watcher *fsnotify.Watcher
var conn *websocket.Conn
func Watch() {
// Listen watched file change event
if watcher != nil {
watcher.Close()
}
watcher, _ = fsnotify.NewWatcher()
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op == fsnotify.Write {
// Handle when file change
fmt.Println(event.Name)
Build()
if conn != nil {
if err := conn.WriteMessage(websocket.TextMessage, []byte("change")); err != nil {
Warn(err.Error())
}
}
}
case err := <-watcher.Errors:
Warn(err.Error())
}
}
}()
var dirs = []string{"source"}
for _, source := range dirs {
dirPath := filepath.Join(rootPath, source)
symwalk.Walk(dirPath, func(path string, f os.FileInfo, err error) error {
if f.IsDir() {
if err := watcher.Add(path); err != nil {
Warn(err.Error())
}
}
return nil
})
}
}
func Websocket(ctx *ink.Context) {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
if c, err := upgrader.Upgrade(ctx.Res, ctx.Req, nil); err != nil {
Fatal(err)
} else {
conn = c
}
ctx.Stop()
}
func Serve() {
web := ink.New()
web.Get("/articles", ApiListArticle)
web.Get("/articles/:id", ApiGetArticle)
web.Post("/articles", ApiCreateArticle)
web.Put("/articles/:id", ApiSaveArticle)
web.Delete("/articles/:id", ApiRemoveArticle)
web.Get("/live", Websocket)
web.Use(ink.Cors)
web.Get("*", ink.Static(filepath.Join("editor/assets")))
web.Get("*", ink.Static(filepath.Join(rootPath, "public")))
Log("Open http://localhost:" + globalConfig.Build.Port + "/ to preview")
web.Listen(":" + globalConfig.Build.Port)
}