-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmiddleware.go
56 lines (46 loc) · 1.42 KB
/
middleware.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
package aqua
import (
"log"
"net/http"
"os"
"time"
"github.com/tolexo/aero/panik"
)
//statusWriter implemented http ResponseWriter
type statusWriter struct {
http.ResponseWriter
status int
}
//WriteHeader implementing http ResponseWriter method
func (w *statusWriter) WriteHeader(status int) {
w.status = status
w.ResponseWriter.WriteHeader(status)
}
func ModAccessLog(path string) func(http.Handler) http.Handler {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
panik.On(err)
l := log.New(f, "", log.LstdFlags)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
wrapedWriter := &statusWriter{ResponseWriter: w, status: http.StatusOK}
next.ServeHTTP(wrapedWriter, r)
l.Printf("%s %s %v %.3f", r.Method, r.RequestURI, wrapedWriter.status, time.Since(start).Seconds())
})
}
}
func ModSlowLog(path string, msec int) func(http.Handler) http.Handler {
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
panik.On(err)
l := log.New(f, "", log.LstdFlags)
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
next.ServeHTTP(w, r)
dur := time.Since(start).Seconds() - float64(msec)/1000.0
if dur > 0 {
l.Printf("%s %s %.3f", r.Method, r.RequestURI, time.Since(start).Seconds())
}
})
}
}