-
Notifications
You must be signed in to change notification settings - Fork 22
/
http_middleware.go
49 lines (40 loc) · 1.16 KB
/
http_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
package main
import (
log "github.com/Sirupsen/logrus"
"github.com/urfave/negroni"
"net/http"
"runtime"
"time"
)
func CutServiceMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
if gHttpServer.stopped {
log.Info("Http server is quiting, ignore this request")
rw.WriteHeader(http.StatusServiceUnavailable)
return
}
gHttpServer.wg.Add(1)
next(rw, r)
gHttpServer.wg.Done()
}
func RecoveryMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
defer func() {
if err := recover(); err != nil {
if rw.Header().Get("Content-Type") == "" {
rw.Header().Set("Content-Type", "text/plain; charset=utf-8")
}
rw.WriteHeader(http.StatusInternalServerError)
stack := make([]byte, 1024*8)
stack = stack[:runtime.Stack(stack, false)]
f := "PANIC: %s\n%s"
log.Errorf(f, err, stack)
}
}()
next(rw, r)
}
func LoggerMiddleware(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
start := time.Now()
log.Debugf("Request recived %s %s", r.Method, r.URL.Path)
next(rw, r)
res := rw.(negroni.ResponseWriter)
log.Debugf("Request completed %v in %v", res.Status(), time.Since(start))
}