-
Notifications
You must be signed in to change notification settings - Fork 1
/
static2.go_
76 lines (65 loc) · 1.85 KB
/
static2.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
package gohm
import (
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
func StaticHandler2(virtualRoot, fileSystemRoot string) http.Handler {
log.Printf("[DEBUG] static handler: virtual root: %q; file system root: %q\n", virtualRoot, fileSystemRoot)
fileServingHandler := http.FileServer(http.Dir(fileSystemRoot))
const requestHeader = "Accept-Encoding"
const responseHeader = "Content-Encoding"
types := []struct {
name, suffix string
}{
{"gzip", ".gz"},
{"flubber", ".fl"},
}
return http.StripPrefix(virtualRoot, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") {
Error(w, r.URL.Path, http.StatusForbidden)
return
}
acceptableEncodings := r.Header.Get(requestHeader)
if acceptableEncodings == "" {
fileServingHandler.ServeHTTP(w, r)
return
}
for _, ty := range types {
if strings.Contains(acceptableEncodings, ty.name) {
log.Printf("[DEBUG] requested: %q", ty.name)
stub := filepath.Join(fileSystemRoot, r.URL.Path)
pathname := filepath.Join(fileSystemRoot, r.URL.Path+ty.suffix)
fh, err := os.Open(pathname)
if err != nil {
continue
}
log.Printf("[DEBUG] pathname: %q", pathname)
// fi, err := fh.Stat()
// if err != nil {
// _ = fh.Close()
// continue
// }
// log.Printf("[DEBUG] %#v", fi)
w.Header().Set(responseHeader, ty.name)
// determine content type
if _, err2 := io.Copy(w, fh); err == nil {
err = err2
}
if err2 := fh.Close(); err == nil {
err = err2
}
if err != nil {
Error(w, r.URL.Path+": "+err.Error(), http.StatusInternalServerError)
}
return
}
}
// Could not find a pre-compressed file that matches the requested compression algorithm.
// TODO: Consider compressing on the fly...
fileServingHandler.ServeHTTP(w, r)
}))
}