[#174] Log unmatched requests

Signed-off-by: Denis Kirillov <d.kirillov@yadro.com>
This commit is contained in:
Denis Kirillov 2023-07-19 17:55:00 +03:00
parent 80c4982bd4
commit 62e6b49254

View file

@ -111,7 +111,7 @@ func AttachChi(api *chi.Mux, domains []string, throttle middleware.ThrottleOpts,
}
api.Mount("/", hr)
attachErrorHandler(api, h, center, log, appMetrics)
attachErrorHandler(api)
}
func named(name string, handlerFunc http.HandlerFunc) http.HandlerFunc {
@ -122,38 +122,30 @@ func named(name string, handlerFunc http.HandlerFunc) http.HandlerFunc {
}
}
func setErrorAPI(apiName string, h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := s3middleware.SetReqInfo(r.Context(), &s3middleware.ReqInfo{API: apiName})
h.ServeHTTP(w, r.WithContext(ctx))
}
}
// If none of the http routes match respond with appropriate errors.
func errorResponseHandler(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
reqInfo := s3middleware.GetReqInfo(ctx)
desc := fmt.Sprintf("Unknown API request at %s", r.URL.Path)
s3middleware.WriteErrorResponse(w, s3middleware.GetReqInfo(r.Context()), errors.Error{
s3middleware.WriteErrorResponse(w, reqInfo, errors.Error{
Code: "UnknownAPIRequest",
Description: desc,
HTTPStatusCode: http.StatusBadRequest,
})
if log := s3middleware.GetReqLog(ctx); log != nil {
log.Error("request unmatched", zap.String("method", reqInfo.API))
}
}
// attachErrorHandler set NotFoundHandler and MethodNotAllowedHandler for chi.Router.
func attachErrorHandler(api *chi.Mux, h Handler, center auth.Center, log *zap.Logger, appMetrics *metrics.AppMetrics) {
middlewares := chi.Middlewares{
s3middleware.Auth(center, log),
s3middleware.Metrics(log, h.ResolveBucket, appMetrics),
}
var errorHandler http.Handler = http.HandlerFunc(errorResponseHandler)
for i := len(middlewares) - 1; i >= 0; i-- {
errorHandler = middlewares[i](errorHandler)
}
func attachErrorHandler(api *chi.Mux) {
errorHandler := http.HandlerFunc(errorResponseHandler)
// If none of the routes match, add default error handler routes
api.NotFound(setErrorAPI("NotFound", errorHandler))
api.MethodNotAllowed(setErrorAPI("MethodNotAllowed", errorHandler))
api.NotFound(named("NotFound", errorHandler))
api.MethodNotAllowed(named("MethodNotAllowed", errorHandler))
}
func bucketRouter(h Handler, log *zap.Logger) chi.Router {
@ -302,6 +294,8 @@ func bucketRouter(h Handler, log *zap.Logger) chi.Router {
DefaultHandler(named("DeleteBucket", h.DeleteBucketHandler)))
})
attachErrorHandler(bktRouter)
return bktRouter
}
@ -387,5 +381,7 @@ func objectRouter(h Handler, l *zap.Logger) chi.Router {
DefaultHandler(named("DeleteObject", h.DeleteObjectHandler)))
})
attachErrorHandler(objRouter)
return objRouter
}