-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
57 lines (47 loc) · 1.22 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
57
package rest
import (
"github.com/go-chi/chi/v5/middleware"
"log"
"net/http"
"net/url"
"strings"
"sync/atomic"
"time"
)
// Logger - log all requests
func Logger(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, 1)
start := time.Now()
defer func() {
statusCode := ww.Status()
if statusCode == 0 {
statusCode = 200
}
uri := r.URL.String()
if qun, e := url.QueryUnescape(uri); e == nil {
uri = qun
}
duration := time.Now().Sub(start)
log.Printf("[DEBUG] %s - %s - %s - %v - %v", r.Method, uri, GetAddr(r), statusCode, duration)
}()
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
// Readiness - middleware for the readiness probe
func Readiness(endpoint string, isReady *atomic.Value) func(http.Handler) http.Handler {
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" && strings.EqualFold(r.URL.Path, endpoint) {
if isReady == nil || !isReady.Load().(bool) {
ErrorResponse(w, r, http.StatusServiceUnavailable, nil, "")
return
}
OkResponse(w)
return
}
h.ServeHTTP(w, r)
})
}
}