-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathproxy.go
284 lines (244 loc) · 6.23 KB
/
proxy.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"errors"
"fmt"
"html/template"
"net"
"net/http"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"github.com/qrtz/livedev/gosource"
)
type proxy struct {
addr *net.TCPAddr
port int
servers map[string]*Server
defaultServer *Server
codeViewerMux *serveMux
}
type serveMux struct {
Handler *http.ServeMux
Addr string
Port int
}
func newProxy(port int, servers map[string]*Server, defaultServer *Server) *proxy {
p := &proxy{
port: port,
servers: servers,
defaultServer: defaultServer,
}
p.codeViewerMux = codeViewer(p.servers)
return p
}
// ServerError represents a server error
type ServerError struct {
Message string
Name string
Data []TextNode
}
// TextNode represents a text node
type TextNode struct {
Text, Link, Line string
}
func resolvePath(f string, dirs []string) (dir, path string) {
isAbs := filepath.IsAbs(f)
for _, dir := range dirs {
if isAbs {
if strings.HasPrefix(f, dir) {
return dir, strings.TrimPrefix(f, dir)[1:]
}
} else if p := filepath.Join(dir, f); fileExists(p) {
return dir, strings.TrimPrefix(p, dir)[1:]
}
}
return dir, path
}
func parseError(gopaths []string, prefix string, err []byte) (lines []TextNode) {
var b []byte
var ln []byte
var filename string
for _, c := range err {
switch c {
case ':':
if len(ln) == 0 {
s := strings.TrimSpace(string(b))
if dir, f := resolvePath(s, gopaths); len(dir) > 0 {
filename = filepath.Join(prefix, f)
}
}
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
if len(filename) > 0 {
ln = append(ln, c)
}
case '\n':
lines = append(lines, TextNode{Text: string(append(b, c))})
b = b[:0]
default:
if len(filename) > 0 {
lines = append(lines, TextNode{Text: string(b), Link: filename, Line: string(ln)})
b = b[:0]
filename = filename[:0]
ln = ln[:0]
}
}
if c != '\n' {
b = append(b, c)
}
}
if len(b) > 0 {
lines = append(lines, TextNode{Text: string(b)})
}
return lines
}
func lastIndexOf(s string, b byte) int {
for i := len(s) - 1; i > 0; i-- {
if s[i] == b {
return i
}
}
return -1
}
func splitPathLine(path string) (string, int64, error) {
if i := lastIndexOf(path, ':'); i >= 0 {
line, err := strconv.ParseInt(path[i+1:], 10, 32)
return path[:i], line, err
}
return path, -1, errors.New("No line number")
}
func codeViewer(servers map[string]*Server) *serveMux {
managerMux := &serveMux{Handler: http.NewServeMux()}
managerMux.Handler.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var data struct {
Title string
Lines []*gosource.Line
ErrorLine int64
}
if len(r.URL.Path) == 1 {
http.NotFound(w, r)
return
}
hostname, _, _ := net.SplitHostPort(r.Host)
srv, ok := servers[hostname]
if !ok {
http.Error(w, "Server not found: "+hostname, http.StatusNotFound)
return
}
path, line, err := splitPathLine(r.URL.Path[1:])
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
data.ErrorLine = line
srcDirs := append(srv.context.SrcDirs(), srv.targetDir)
if dir, path := resolvePath(path, srcDirs); len(dir) > 0 {
filename := filepath.Join(dir, path)
lines, err := gosource.Parse(filename)
if err == nil {
data.Lines = lines
}
data.Title = "Source: " + path
}
if len(data.Lines) > 0 {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
codeviewerTemplate.Execute(w, data)
} else {
http.Error(w, "File not found: "+path, http.StatusNotFound)
}
})
return managerMux
}
func (p *proxy) handleError(w http.ResponseWriter, err ServerError, code int) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.WriteHeader(code)
// create template context
templateData := make(map[string]interface{})
templateData["Name"] = err.Name
templateData["Message"] = err.Message
templateData["Data"] = err.Data
templateData["LiveReloadHTML"] = template.HTML(fmt.Sprintf(liveReloadHTML, p.port))
errTemplate.Execute(w, templateData)
}
func (p *proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var (
srv *Server
host = r.Host
)
defer func() {
if err := recover(); err != nil {
var buf [2 << 10]byte
errData := ServerError{Name: "Unknown Error"}
if srv != nil {
addr := net.JoinHostPort(srv.host, strconv.Itoa(p.codeViewerMux.Port)) + "/"
errData.Data = parseError(append(srv.context.SrcDirs(), srv.targetDir), addr, buf[:runtime.Stack(buf[:], false)])
}
p.handleError(w, errData, http.StatusInternalServerError)
}
}()
if h, _, err := net.SplitHostPort(r.Host); err == nil {
host = h
}
srv = p.servers[host]
if srv == nil {
if p.defaultServer != nil {
srv = p.defaultServer
} else {
http.Error(w, fmt.Sprintf(`Host not found "%s"`, host), http.StatusNotFound)
return
}
}
if err := srv.ServeHTTP(w, r); err != nil {
if r.Header.Get("Upgrade") == "websocket" {
conn, buf, err := w.(http.Hijacker).Hijack()
writeWebSocketError(buf, err, http.StatusInternalServerError)
conn.Close()
} else {
errData := ServerError{Name: "Error"}
errData.Data = parseError(append(srv.context.SrcDirs(), srv.targetDir), net.JoinHostPort(srv.host, strconv.Itoa(p.codeViewerMux.Port)), []byte(err.Error()))
p.handleError(w, errData, http.StatusInternalServerError)
}
}
}
func (p *proxy) shutdown() {
var wg sync.WaitGroup
for _, srv := range p.servers {
wg.Add(1)
go func(s *Server) {
defer wg.Done()
s.shutdown()
}(srv)
}
wg.Wait()
}
func (p *proxy) ListenAndServe() error {
addr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort("", strconv.Itoa(p.port)))
if err != nil {
return err
}
p.addr = addr
done := make(chan error, 1)
go func() {
done <- http.ListenAndServe(p.addr.String(), p)
}()
select {
case err := <-done:
done <- err
default:
if addr, err := findAvailablePort(); err == nil {
go func(port int) {
p.codeViewerMux.Port = port
p.codeViewerMux.Addr = net.JoinHostPort("", strconv.Itoa(port))
done <- http.ListenAndServe(p.codeViewerMux.Addr, p.codeViewerMux.Handler)
}(addr.Port)
} else {
done <- err
}
}
err = <-done
p.shutdown()
return err
}