-
Notifications
You must be signed in to change notification settings - Fork 0
/
webserver.go
108 lines (89 loc) · 1.92 KB
/
webserver.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
107
108
package webserver
import (
"log"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"github.com/fsnotify/fsnotify"
)
type New struct {
Dir string
Port string
Log bool
}
func (s *New) Start() {
if !hasHTMLFilesInDir(s.Dir) {
log.Println("No .html files found in the directory")
return
}
go s.startHTTPServer()
watcher := setupFileWatcher(s.Dir)
defer watcher.Close()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
<-stop
log.Println("Shutting down...")
}
func (s *New) startHTTPServer() {
http.HandleFunc("/", s.handler)
log.Printf("Hello Onii-chan! Server running on localhost:%s\n\n", s.Port)
log.Fatal(http.ListenAndServe(":"+s.Port, nil))
}
func (s *New) handler(w http.ResponseWriter, r *http.Request) {
if s.Log {
log.Printf("%s %s", r.Method, r.URL.Path)
}
path := r.URL.Path
if path == "" || path == "/" || strings.HasSuffix(path, "/") {
path = filepath.Join(s.Dir, path, "index.html")
http.ServeFile(w, r, path)
return
}
if !strings.Contains(path, ".") {
path += ".html"
}
http.ServeFile(w, r, filepath.Join(s.Dir, path))
}
func setupFileWatcher(dir string) *fsnotify.Watcher {
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && filepath.Ext(path) == ".html" {
err = watcher.Add(path)
if err != nil {
log.Println(err)
}
}
return nil
})
if err != nil {
log.Fatal(err)
}
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&(fsnotify.Write|fsnotify.Create) != 0 {
log.Println("File modified:", event.Name)
}
}
}
}()
return watcher
}
func hasHTMLFilesInDir(dir string) bool {
files, err := filepath.Glob(filepath.Join(dir, "*.html"))
if err != nil {
log.Println(err)
return false
}
return len(files) > 0
}