forked from InkProject/ink
-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve.go
106 lines (97 loc) · 2.51 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"os"
"path/filepath"
"github.com/InkProject/ink.go"
"github.com/facebookgo/symwalk"
"github.com/fsnotify/fsnotify"
"github.com/gorilla/websocket"
"github.com/taadis/oper"
)
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
Log(event.Name)
ParseGlobalConfigWrap(rootPath, true)
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{
filepath.Join(rootPath, "source"),
filepath.Join(themePath, "bundle"),
}
var files = []string{
filepath.Join(rootPath, "config.yml"),
filepath.Join(themePath),
}
for _, source := range dirs {
symwalk.Walk(source, func(path string, f os.FileInfo, err error) error {
if f.IsDir() {
if err := watcher.Add(path); err != nil {
Warn(err.Error())
}
}
return nil
})
}
for _, source := range files {
if err := watcher.Add(source); err != nil {
Warn(err.Error())
}
}
}
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 {
Warn(err)
} else {
conn = c
}
ctx.Stop()
}
func Serve() {
// editorWeb := ink.New()
//
// editorWeb.Get("/articles", ApiListArticle)
// editorWeb.Get("/articles/:id", ApiGetArticle)
// editorWeb.Post("/articles", ApiCreateArticle)
// editorWeb.Put("/articles/:id", ApiSaveArticle)
// editorWeb.Delete("/articles/:id", ApiRemoveArticle)
// editorWeb.Get("/config", ApiGetConfig)
// editorWeb.Put("/config", ApiSaveConfig)
// editorWeb.Post("/upload", ApiUploadFile)
// editorWeb.Use(ink.Cors)
// editorWeb.Get("*", ink.Static(filepath.Join("editor/assets")))
// Log("Access http://localhost:" + globalConfig.Build.Port + "/ to open editor")
// go editorWeb.Listen(":2333")
previewWeb := ink.New()
previewWeb.Get("/live", Websocket)
previewWeb.Get("*", ink.Static(filepath.Join(rootPath, globalConfig.Build.Output)))
uri := "http://localhost:" + globalConfig.Build.Port + "/"
Log("Access " + uri + " to open preview")
oper.Access(uri)
previewWeb.Listen(":" + globalConfig.Build.Port)
}