@@ -6,45 +6,67 @@ import (
66 "time"
77
88 "github.com/distrobyte/gerry/internal/config"
9- "github.com/justinas/alice"
9+ "github.com/go-chi/chi/v5"
10+ "github.com/go-chi/chi/v5/middleware"
11+ "github.com/google/uuid"
12+ "github.com/rs/zerolog"
1013 "github.com/rs/zerolog/hlog"
1114 "github.com/rs/zerolog/log"
1215)
1316
1417func initHTTPServer () {
15- c := alice .New ()
16-
17- c = c .Append (hlog .NewHandler (log .Logger .With ().Str ("component" , "http" ).Logger ()))
18-
19- c = c .Append (hlog .AccessHandler (func (r * http.Request , status , size int , duration time.Duration ) {
20- hlog .FromRequest (r ).Info ().
21- Str ("method" , r .Method ).
22- Stringer ("url" , r .URL ).
23- Str ("Cf-Connecting-Ip" , r .Header .Get ("Cf-Connecting-Ip" )).
24- Int ("status" , status ).
25- Int ("size" , size ).
26- Dur ("duration" , duration ).
27- Msg ("" )
28- }))
29- c = c .Append (hlog .RemoteAddrHandler ("ip" ))
30- c = c .Append (hlog .UserAgentHandler ("user-agent" ))
31- c = c .Append (hlog .RequestIDHandler ("req_id" , "Request-Id" ))
32- c = c .Append (hlog .RefererHandler ("referer" ))
33-
34- // create a new mux
35- mux := http .NewServeMux ()
36-
37- mux .HandleFunc ("GET /health" , healthHandler )
38- mux .HandleFunc ("GET /karting" , kartingHTMLHandler )
39- mux .HandleFunc ("GET /karting.svg" , kartingSVGHandler )
40- mux .HandleFunc ("GET /karting.png" , kartingPNGHandler )
41- mux .HandleFunc ("GET /karting.json" , kartingJSONHandler )
42- mux .HandleFunc ("GET /*" , notFoundHandler )
43- mux .HandleFunc ("/*" , methodNotAllowedHandler )
44-
45- http .Handle ("/" , c .Then (mux ))
46-
47- log .Info ().Msg ("http server initialized. listening on port " + fmt .Sprintf ("%d" , config .GetHTTPPort ()))
18+
19+ r := chi .NewRouter ()
20+ r .Use (requestIDMiddleware )
21+ r .Use (zerologMiddleware )
22+
23+ r .Get ("/" , func (w http.ResponseWriter , r * http.Request ) {
24+ // use the kartingHTML handler to serve the main page
25+ kartingHTMLHandler (w , r )
26+ })
27+
28+ r .Get ("/health" , healthHandler )
29+ r .Get ("/karting" , kartingHTMLHandler )
30+ r .Get ("/karting.svg" , kartingSVGHandler )
31+ r .Get ("/karting.png" , kartingPNGHandler )
32+ r .Get ("/karting.json" , kartingJSONHandler )
33+ r .NotFound (notFoundHandler )
34+ r .MethodNotAllowed (methodNotAllowedHandler )
35+
36+ log .Info ().Msgf ("Starting server on port %d" , config .GetHTTPPort ())
37+ log .Fatal ().Err (http .ListenAndServe (fmt .Sprintf (":%d" , config .GetHTTPPort ()), r )).Msg ("" )
38+ log .Info ().Msgf ("Server started on port %d" , config .GetHTTPPort ())
39+ }
40+
41+ func requestIDMiddleware (next http.Handler ) http.Handler {
42+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
43+ requestID := uuid .New ().String ()
44+ logger := log .With ().Str ("request_id" , requestID ).Logger ()
45+ r = r .WithContext (logger .WithContext (r .Context ()))
46+ w .Header ().Set ("X-Request-ID" , requestID )
47+ next .ServeHTTP (w , r )
48+ })
49+ }
50+
51+ func zerologMiddleware (next http.Handler ) http.Handler {
52+ return http .HandlerFunc (func (w http.ResponseWriter , r * http.Request ) {
53+ start := time .Now ()
54+ ww := middleware .NewWrapResponseWriter (w , r .ProtoMajor )
55+
56+ logger := zerolog .Ctx (r .Context ())
57+ defer func () {
58+ logger .Info ().
59+ Str ("method" , r .Method ).
60+ Str ("path" , r .URL .Path ).
61+ Int ("status" , ww .Status ()).
62+ Int ("bytes" , ww .BytesWritten ()).
63+ Str ("remote" , r .RemoteAddr ).
64+ Dur ("duration" , time .Since (start )).
65+ Msg ("handled request" )
66+ }()
67+
68+ next .ServeHTTP (ww , r )
69+ })
4870}
4971
5072func ServeHTTP () {
@@ -66,6 +88,11 @@ func healthHandler(w http.ResponseWriter, r *http.Request) {
6688}
6789
6890func kartingHTMLHandler (w http.ResponseWriter , r * http.Request ) {
91+ if r .Method != http .MethodGet {
92+ methodNotAllowedHandler (w , r )
93+ return
94+ }
95+
6996 w .Header ().Set ("Content-Type" , "text/html" )
7097 htmlContent := `
7198 <!DOCTYPE html>
@@ -84,7 +111,6 @@ func kartingHTMLHandler(w http.ResponseWriter, r *http.Request) {
84111 _ , err := w .Write ([]byte (htmlContent ))
85112 if err != nil {
86113 hlog .FromRequest (r ).Error ().Err (err ).Msg ("" )
87- return
88114 }
89115}
90116
0 commit comments