-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathmiddleware.go
More file actions
31 lines (27 loc) · 864 Bytes
/
middleware.go
File metadata and controls
31 lines (27 loc) · 864 Bytes
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
package middleware
import (
"fmt"
"net/http"
"time"
"github.com/practicalgo/code/chap6/complex-server/config"
)
func loggingMiddleware(h http.Handler, c config.AppConfig) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
t1 := time.Now()
h.ServeHTTP(w, r)
requestDuration := time.Now().Sub(t1).Seconds()
c.Logger.Printf("protocol=%s path=%s method=%s duration=%f", r.Proto, r.URL.Path, r.Method, requestDuration)
})
}
func panicMiddleware(h http.Handler, c config.AppConfig) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rValue := recover(); rValue != nil {
c.Logger.Println("panic detected", rValue)
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "Unexpected server error occured")
}
}()
h.ServeHTTP(w, r)
})
}