Skip to content

Commit 45f77e2

Browse files
committed
Add lesson06 / video01
1 parent 67a1123 commit 45f77e2

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

06-01-http-middlewares/main.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"log"
6+
"net/http"
7+
"time"
8+
)
9+
10+
const httpAddr = ":8080"
11+
12+
func main() {
13+
fmt.Println("Server running on", httpAddr)
14+
15+
mux := http.NewServeMux()
16+
17+
healthHandler := http.HandlerFunc(healthHandler)
18+
mux.Handle("/health", recoveryMiddleware(healthHandler))
19+
20+
log.Fatal(http.ListenAndServe(httpAddr, mux))
21+
}
22+
23+
func healthHandler(w http.ResponseWriter, _ *http.Request) {
24+
w.WriteHeader(http.StatusOK)
25+
w.Write([]byte("everything is ok!"))
26+
}
27+
28+
func recoveryMiddleware(next http.Handler) http.Handler {
29+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
30+
defer func() {
31+
if err := recover(); err != nil {
32+
log.Printf("[Middleware] %s panic recovered:\n%s\n",
33+
time.Now().Format("2006/01/02 - 15:04:05"), err)
34+
35+
w.WriteHeader(http.StatusInternalServerError)
36+
}
37+
}()
38+
39+
next.ServeHTTP(w, r)
40+
})
41+
}

0 commit comments

Comments
 (0)