-
Notifications
You must be signed in to change notification settings - Fork 153
/
wrap_other.go
63 lines (53 loc) · 1.64 KB
/
wrap_other.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
package main
import (
"net/http"
"os"
"reflect"
"runtime"
"time"
stdlog "log"
log "github.com/Sirupsen/logrus"
uuid "github.com/satori/go.uuid"
)
var logger = stdlog.New(os.Stdout, "[TEST] ", stdlog.Ldate|stdlog.Ltime)
func wrapFunc(fn func(w http.ResponseWriter, req *http.Request)) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
fn(w, req)
logger.Printf("%s %s | Took %s", req.Method, req.URL.Path, time.Since(start))
}
}
func wrapFuncWithLogrus(fn func(w http.ResponseWriter, req *http.Request)) func(w http.ResponseWriter, req *http.Request) {
return func(w http.ResponseWriter, req *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("recovered from panic: %+v / %+v", err, req)
// http.Error(w, http.StatusText(500), 500)
}
}()
start := time.Now()
fn(w, req) // execute the handler
took := time.Since(start)
// ip, err := getIP(req)
// if err != nil {
// log.Warnf("getIP error: %v", err)
// }
log.WithFields(log.Fields{
"event_type": runtime.FuncForPC(reflect.ValueOf(fn).Pointer()).Name(),
"referrer": req.Referer(),
"ua": req.UserAgent(),
"method": req.Method,
"path": req.URL.Path,
"ip": req.RemoteAddr,
"real_ip": getRealIP(req),
"uuid": uuid.NewV4(),
}).Debugf("took %s", took)
}
}
func wrapHandlerFunc(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
start := time.Now()
h.ServeHTTP(w, req)
logger.Printf("%s %s | Took %s", req.Method, req.URL.Path, time.Since(start))
}
}