-
Notifications
You must be signed in to change notification settings - Fork 6
/
util.go
135 lines (115 loc) · 2.55 KB
/
util.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
package main
import (
"bufio"
"crypto/sha1"
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"os"
"path/filepath"
"strings"
)
func findAvailablePort() (*net.TCPAddr, error) {
l, err := net.Listen("tcp", ":0")
if err == nil {
defer l.Close()
addr := l.Addr()
if a, ok := addr.(*net.TCPAddr); ok {
return a, nil
}
return nil, fmt.Errorf("Unable to obtain a valid tcp port. %v", addr)
}
return nil, err
}
// HasPrefix is a convenient wrapper for strings.HasPrefix to test a list of prefixes
func hasPrefix(s string, prefixes []string) bool {
if len(s) == 0 || len(prefixes) == 0 {
return false
}
for _, p := range prefixes {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}
// ImportRoots returns a list of directories that contain a sub-directory named "src"
func importRoots(path string) (roots []string) {
dir, _ := filepath.Split(filepath.Clean(path))
for i, p := len(dir)-1, len(dir); i > 0; i-- {
if os.IsPathSeparator(dir[i]) {
if dir[i+1:p] == "src" {
roots = append(roots, dir[:i])
}
p = i
}
}
return roots
}
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
return !os.IsNotExist(err)
}
return true
}
var tags = [][]byte{
bytesReverse([]byte("</HTML>")),
bytesReverse([]byte("</BODY>")),
}
func appendHTML(data, code []byte) []byte {
offset := len(data) - 1
DONE:
for _, tag := range tags {
for ; offset > len(tag) && isWhiteSpace(data[offset]); offset-- {
}
for i := 0; offset > 0 && i < len(tag); offset-- {
b := data[offset]
if !isWhiteSpace(b) {
t := tag[i]
if t >= 'A' && t <= 'Z' {
b &= 0xDF
}
if b != t {
// Not well-formed HTML
offset = len(data) - 1
break DONE
}
i++
}
}
}
if offset < len(data) {
offset++
}
data = append(data[:offset], append(code, data[offset:]...)...)
return data
}
func isWhiteSpace(b byte) bool {
switch b {
case ' ', '\n', '\t', '\r', '\x0c':
return true
}
return false
}
func bytesReverse(b []byte) []byte {
for i, c := range b[:len(b)/2] {
b[i], b[len(b)-i-1] = b[len(b)-i-1], c
}
return b
}
func writeWebSocketError(w io.Writer, err error, code int) {
b := bufio.NewWriter(w)
fmt.Fprintf(b, "HTTP/1.1 %03d %s\r\n", code, http.StatusText(code))
b.WriteString("\r\n")
b.WriteString(err.Error())
b.Flush()
}
const websocketGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
func generateWebsocketAcceptKey(key string) string {
hash := sha1.New()
hash.Write([]byte(key))
hash.Write([]byte(websocketGUID))
return base64.StdEncoding.EncodeToString(hash.Sum(nil))
}