-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalfred.go
More file actions
119 lines (96 loc) · 2.23 KB
/
alfred.go
File metadata and controls
119 lines (96 loc) · 2.23 KB
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
package alfred
import (
"fmt"
"net/http"
"os"
"path"
"time"
"github.com/codemodus/rwap"
)
// Alfred ...
type Alfred struct {
fs http.Handler
cnf *responseConfig
}
// New ...
func New(dir string) *Alfred {
return &Alfred{
fs: http.FileServer(http.Dir(dir)),
cnf: &responseConfig{
dir: dir,
index: "index.html",
notFound: []byte("not found"),
},
}
}
func (a *Alfred) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w = newResponseWriterWrap(w, r, a.cnf)
a.fs.ServeHTTP(w, r)
}
type responseConfig struct {
dir string
index string
notFound []byte
}
type responseWriterWrap struct {
http.ResponseWriter
r *http.Request
cnf *responseConfig
hit bool
}
func newResponseWriterWrap(w http.ResponseWriter, r *http.Request, cnf *responseConfig) *responseWriterWrap {
return &responseWriterWrap{
ResponseWriter: w,
r: r,
cnf: cnf,
}
}
func (w *responseWriterWrap) WriteHeader(code int) {
if code == http.StatusNotFound && path.Ext(w.r.URL.Path) == "" {
w.hit = true
return
}
w.ResponseWriter.WriteHeader(code)
}
func (w *responseWriterWrap) Write(b []byte) (int, error) {
if !w.hit {
return w.ResponseWriter.Write(b)
}
f, st, err := openFileWithStats(path.Join(w.cnf.dir, w.cnf.index))
if err != nil {
w.ResponseWriter.WriteHeader(http.StatusNotFound)
return w.ResponseWriter.Write(w.cnf.notFound)
}
w.ResponseWriter.Header().Set("Content-Type", "text/html")
http.ServeContent(w.ResponseWriter, w.r, f.Name(), st.ModTime(), f)
return int(st.Size()), nil
}
func openFileWithStats(filename string) (*os.File, os.FileInfo, error) {
f, err := os.Open(filename)
if err != nil {
return nil, nil, err
}
st, err := f.Stat()
if err != nil {
return nil, nil, err
}
return f, st, nil
}
// LogAccess ...
func LogAccess(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t := time.Now()
rw := rwap.New(w)
next.ServeHTTP(rw, r)
var stts int
rstts := rw.Status()
if rstts > 0 {
stts = rstts
}
afmt := "%3d\t%-7s\t%08.3f\t%s\n"
fmt.Printf(afmt, stts, r.Method, floatDurSince(t), r.URL.Path)
})
}
func floatDurSince(t time.Time) float64 {
return float64(time.Since(t).Nanoseconds()) / 1000000
}