-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
204 lines (175 loc) · 4.84 KB
/
server.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"flag"
"fmt"
"go/ast"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"./parse"
"github.com/gorilla/websocket"
)
type ClientError struct {
Error string `json:"error"`
}
const (
// Time allowed to write the file to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Poll file for changes with this period.
filePeriod = 2 * time.Second
port = "8080"
)
var (
addr = flag.String("addr", ":"+port, "http service address")
dirnames []string
filenames []string
upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
// allow cross site requests
CheckOrigin: func(r *http.Request) bool {
return true
},
}
pkgs map[string]*ast.Package
// TODO yes global error state is disgusting. Sue me.
globError error
)
func readFileIfModified(lastMod time.Time) (*parse.ClientStruct, time.Time, error) {
if len(filenames) == 0 {
return runParser(lastMod, nil)
}
for _, filename := range filenames {
fi, err := os.Stat(filename)
if err != nil || fi.ModTime().After(lastMod) {
// if err != nil {
fmt.Printf("Detected file change: %s, %s, %s \n", fi.ModTime(), lastMod, err)
return runParser(fi.ModTime(), err)
}
}
return nil, lastMod, nil
}
func runParser(lastMod time.Time, err error) (*parse.ClientStruct, time.Time, error) {
// TODO handle error
var clientstruct *parse.ClientStruct
clientstruct, pkgs = parse.GetStructsDirName(dirnames)
// Set new files to watch
// TODO race conditions?
filenames = []string{}
for _, clientpkg := range clientstruct.Packages {
for _, clientfile := range clientpkg.Files {
if strings.HasSuffix(clientfile.Name, "_test.go") {
// fmt.Printf("Ignore file: %s\n", clientfile.Name)
} else {
filenames = append(filenames, clientfile.Name)
}
}
}
return clientstruct, lastMod, err
}
func reader(ws *websocket.Conn) {
defer ws.Close()
ws.SetReadLimit(1000 * 512)
ws.SetReadDeadline(time.Now().Add(pongWait))
ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
// fmt.Println("begin")
// _, message, _ := ws.ReadMessage()
// if err != nil {
// fmt.Println(err)
// break;
// }
var message parse.ClientStruct
if err := ws.ReadJSON(&message); err != nil {
fmt.Println(err)
break
}
globError = parse.WriteClientPackages(dirnames, pkgs, message.Packages)
fmt.Println("Received client packages")
}
}
func writer(ws *websocket.Conn, lastMod time.Time) {
pingTicker := time.NewTicker(pingPeriod)
fileTicker := time.NewTicker(filePeriod)
defer func() {
pingTicker.Stop()
fileTicker.Stop()
ws.Close()
}()
for {
select {
case <-fileTicker.C:
var clientstruct *parse.ClientStruct
//var p []byte
// var err error
clientstruct, lastMod, _ = readFileIfModified(lastMod)
// TODO err
if globError != nil {
fmt.Println("error detected", globError.Error())
ws.SetWriteDeadline(time.Now().Add(writeWait))
ws.WriteJSON(ClientError{Error: globError.Error()})
globError = nil
} else if clientstruct != nil {
fmt.Println("Pushing file change to client.")
ws.SetWriteDeadline(time.Now().Add(writeWait))
ws.WriteJSON(clientstruct)
//if err := ws.WriteMessage(websocket.TextMessage, p); err != nil {
// return
//}
}
case <-pingTicker.C:
ws.SetWriteDeadline(time.Now().Add(writeWait))
if err := ws.WriteMessage(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
func serveWs(w http.ResponseWriter, r *http.Request) {
fmt.Println("Begin websocket server")
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
if _, ok := err.(websocket.HandshakeError); !ok {
log.Println(err)
}
return
}
var lastMod time.Time
if n, err := strconv.ParseInt(r.FormValue("lastMod"), 10, 64); err == nil {
lastMod = time.Unix(0, n*int64(time.Millisecond))
}
go writer(ws, lastMod)
reader(ws)
}
func main() {
flag.Parse()
if flag.NArg() < 1 {
log.Fatal("dirname not specified")
}
dirnames = flag.Args()
http.Handle("/", http.FileServer(http.Dir("./app/build")))
http.HandleFunc("/ws", serveWs)
fmt.Println("Listening on http://localhost:" + port)
// open webpage automatically
// switch runtime.GOOS {
// case "linux":
// exec.Command("xdg-open", "http://localhost:"+port).Run()
// case "windows":
// exec.Command("explorer", "http://localhost:"+port).Run()
// default:
// exec.Command("open", "http://localhost:"+port).Run()
// }
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal(err)
}
}