-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
127 lines (100 loc) · 2.18 KB
/
main.go
File metadata and controls
127 lines (100 loc) · 2.18 KB
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"fmt"
"frsh/pkg/lib"
"net/http"
"os"
"path/filepath"
"strings"
"sync"
"github.com/gorilla/websocket"
)
func setPort() string {
return "8080"
}
func fileResponse(w http.ResponseWriter, r *http.Request) {
filePath := "." + r.URL.Path
m := lib.MIMEType
fc := lib.FileContent
wc := lib.WebsocketsClient
p := setPort()
mimeType := m(filePath)
if mimeType == "text/html" {
//NOTE:
//just a quick patch to fix for recognize *.html as directory
//instead of file
ext := filepath.Ext(r.URL.Path)
if ext == ".html" {
filePath = "." + r.URL.Path
} else {
filePath = "." + r.URL.Path + "/index.html"
}
contentOrigin := fc(filePath)
content := strings.Replace(contentOrigin, "</head>", wc(p)+"</head>", -1)
w.Header().Set("Content-Type", mimeType)
w.Write([]byte(content))
} else if fc(filePath) == "404" {
http.NotFound(w, r)
} else {
filePath := "." + r.URL.Path
content := fc(filePath)
w.Header().Set("Content-Type", mimeType)
w.Write([]byte(content))
}
}
func watchAndReload() {
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
var wg sync.WaitGroup
http.HandleFunc("/livereload", func(w http.ResponseWriter, r *http.Request) {
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
// fmt.Println(err)
}
fileWalkCallback := func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
ignoreDir := lib.DirIgnore
if ignoreDir(path) {
return nil
}
ignoreFile := lib.FileIgnore
if ignoreFile(path) {
return nil
}
wg.Add(1)
go func() {
defer wg.Done()
w := lib.Watch
w(path, func() {
for {
msgType, _, err := c.ReadMessage()
if err != nil {
// fmt.Println(err)
}
err = c.WriteMessage(msgType, []byte("ping"))
if err != nil {
return
}
}
})
}()
return nil
}
fileErr := filepath.Walk("./", fileWalkCallback)
wg.Wait()
if fileErr != nil {
fmt.Println(fileErr)
}
})
}
func main() {
watchAndReload()
port := setPort()
http.HandleFunc("/", fileResponse)
fmt.Println("Listening to port:" + port)
http.ListenAndServe(":"+port, nil)
}