Skip to content

Commit bf2c92b

Browse files
committed
refactor: replace gorilla LoggingHandler with slog middleware
Drop the gorilla/handlers dependency for access logging and use a custom middleware that logs HTTP requests through slog with structured fields (method, path, status, size, duration).
1 parent 46e6189 commit bf2c92b

1 file changed

Lines changed: 34 additions & 3 deletions

File tree

pkg/http/api/v1/handler.go

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,8 @@ import (
66
"fmt"
77
"log/slog"
88
"net/http"
9-
"os"
9+
"time"
1010

11-
"github.com/gorilla/handlers"
1211
"github.com/gorilla/mux"
1312

1413
"github.com/sysdiglabs/harbor-scanner-sysdig-secure/pkg/harbor"
@@ -36,7 +35,7 @@ func NewAPIHandler(adapter scanner.Adapter) http.Handler {
3635
apiV1Router.Methods(http.MethodPost).Path("/scan").HandlerFunc(handler.scan)
3736
apiV1Router.Methods(http.MethodGet).Path("/scan/{scan_request_id}/report").HandlerFunc(handler.getReport)
3837

39-
return handlers.LoggingHandler(os.Stdout, router)
38+
return loggingMiddleware(router)
4039
}
4140

4241
func health(res http.ResponseWriter, _ *http.Request) {
@@ -127,6 +126,38 @@ func (h *requestHandler) getReport(res http.ResponseWriter, req *http.Request) {
127126
_ = json.NewEncoder(res).Encode(vulnerabilityReport)
128127
}
129128

129+
type statusRecorder struct {
130+
http.ResponseWriter
131+
status int
132+
size int
133+
}
134+
135+
func (r *statusRecorder) WriteHeader(code int) {
136+
r.status = code
137+
r.ResponseWriter.WriteHeader(code)
138+
}
139+
140+
func (r *statusRecorder) Write(b []byte) (int, error) {
141+
n, err := r.ResponseWriter.Write(b)
142+
r.size += n
143+
return n, err
144+
}
145+
146+
func loggingMiddleware(next http.Handler) http.Handler {
147+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
148+
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
149+
start := time.Now()
150+
next.ServeHTTP(rec, r)
151+
slog.Info("http request",
152+
"method", r.Method,
153+
"path", r.RequestURI,
154+
"status", rec.status,
155+
"size", rec.size,
156+
"duration", time.Since(start),
157+
)
158+
})
159+
}
160+
130161
func errorResponseFromError(err error) harbor.ErrorResponse {
131162
return harbor.ErrorResponse{
132163
Error: &harbor.ModelError{

0 commit comments

Comments
 (0)