-
Notifications
You must be signed in to change notification settings - Fork 1
/
serve.go
82 lines (67 loc) · 1.29 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
package cmd
import (
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/fsnotify/fsnotify"
"github.com/tatthien/giraffe/engine"
)
var watcher *fsnotify.Watcher
func Serve() {
// Build content
Build()
// Start the server
config, err := engine.LoadConfig(".")
if err != nil {
log.Fatal(err)
}
go func() {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("dist")))
server := http.Server{
Addr: ":" + config.Port,
Handler: mux,
}
fmt.Println("Serving on http://localhost:" + config.Port)
log.Fatal(server.ListenAndServe())
}()
// Watch files changes
watcher, _ = fsnotify.NewWatcher()
defer watcher.Close()
if err := filepath.Walk(".", watchDir); err != nil {
log.Fatal(err)
}
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Println("modified file:", event.Name)
Build()
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
<-done
}
func watchDir(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
if strings.HasPrefix(path, "theme") || strings.HasPrefix(path, "content") {
return watcher.Add(path)
}
}
return nil
}