-
Notifications
You must be signed in to change notification settings - Fork 56
/
util.go
113 lines (94 loc) · 2.54 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
package serverHandler
import (
"compress/flate"
"compress/gzip"
"io"
"mjpclab.dev/ghfs/src/acceptHeaders"
"mjpclab.dev/ghfs/src/util"
"net/http"
"os"
"path"
"regexp"
"strings"
)
func wildcardToRegexp(wildcards []string) (*regexp.Regexp, error) {
if len(wildcards) == 0 {
return nil, nil
}
normalizedWildcards := make([]string, 0, len(wildcards))
for _, wildcard := range wildcards {
if len(wildcard) == 0 {
continue
}
normalizedWildcards = append(normalizedWildcards, util.WildcardToStrRegexp(wildcard))
}
if len(normalizedWildcards) == 0 {
return nil, nil
}
exp := strings.Join(normalizedWildcards, "|")
return regexp.Compile(exp)
}
func NeedResponseBody(method string) bool {
return method != http.MethodHead &&
method != http.MethodOptions &&
method != http.MethodConnect &&
method != http.MethodTrace
}
func getCleanFilePath(requestPath string) (filePath string, ok bool) {
filePath = path.Clean(requestPath)
ok = filePath == path.Base(filePath)
return
}
func getCleanDirFilePath(requestPath string) (filePath string, ok bool) {
filePath = path.Clean(strings.Replace(requestPath, "\\", "/", -1))
ok = filePath[0] != '/' && filePath != "." && filePath != ".." && !strings.HasPrefix(filePath, "../")
return
}
const contentEncGzip = "gzip"
const contentEncDeflate = "deflate"
var encodings = []string{contentEncGzip, contentEncDeflate}
func getCompressWriter(w http.ResponseWriter, r *http.Request) (wr io.WriteCloser, encoding string, ok bool) {
accepts := acceptHeaders.ParseAccepts(r.Header.Get("Accept-Encoding"))
_, encoding, ok = accepts.GetPreferredValue(encodings)
if !ok {
return nil, "", false
}
var err error
switch encoding {
case contentEncGzip:
wr, err = gzip.NewWriterLevel(w, gzip.BestSpeed)
case contentEncDeflate:
wr, err = flate.NewWriter(w, flate.BestSpeed)
default:
return nil, "", false
}
if err != nil {
return nil, "", false
}
return wr, encoding, true
}
func createVirtualFileInfo(name string, refItem os.FileInfo) os.FileInfo {
if refItem != nil {
return createRenamedFileInfo(name, refItem)
} else {
return createPlaceholderFileInfo(name, true)
}
}
func isVirtual(info os.FileInfo) bool {
switch info.(type) {
case placeholderFileInfo, renamedFileInfo:
return true
}
return false
}
func containsItem(infos []os.FileInfo, name string) bool {
for i := range infos {
if util.IsPathEqual(infos[i].Name(), name) {
return true
}
}
return false
}
func shouldServeAsContent(file *os.File, item os.FileInfo) bool {
return file != nil && item != nil && !item.IsDir()
}