From 6527324466b8d53c46e040c7d2f4466d5e0df1c9 Mon Sep 17 00:00:00 2001 From: Vangelis Katikaridis Date: Sat, 9 May 2020 12:06:28 +0200 Subject: [PATCH] #128 make middleware cache abstraction more concrete Signed-off-by: Vangelis Katikaridis --- component/http/cache/route_cache.go | 15 +++++++++++++-- component/http/middleware.go | 10 ++-------- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/component/http/cache/route_cache.go b/component/http/cache/route_cache.go index 4f63ccacb..b47758d4f 100644 --- a/component/http/cache/route_cache.go +++ b/component/http/cache/route_cache.go @@ -3,6 +3,7 @@ package cache import ( "bytes" "errors" + "fmt" "net/http" "time" @@ -116,11 +117,21 @@ func (rw *responseReadWriter) WriteHeader(statusCode int) { } // Handler will wrap the handler func with the route cache abstraction -func Handler(w http.ResponseWriter, r *http.Request, rc *RouteCache, httpHandler http.Handler) (response *handlerResponse, e error) { +func Handler(w http.ResponseWriter, r *http.Request, rc *RouteCache, httpHandler http.Handler) error { req := toCacheHandlerRequest(r) - return handler(httpExecutor(w, r, func(writer http.ResponseWriter, request *http.Request) { + response, err := handler(httpExecutor(w, r, func(writer http.ResponseWriter, request *http.Request) { httpHandler.ServeHTTP(writer, request) }), rc)(req) + if err != nil { + return fmt.Errorf("could not handle request with the cache processor: %v", err) + } + for k, h := range response.Header { + w.Header().Set(k, h[0]) + } + if i, err := w.Write(response.Bytes); err != nil { + return fmt.Errorf("could not Write cache processor result into Response %d: %w", i, err) + } + return nil } // httpExecutor is the function that will create a new response based on a HandlerFunc implementation diff --git a/component/http/middleware.go b/component/http/middleware.go index f623214ba..78f76c408 100644 --- a/component/http/middleware.go +++ b/component/http/middleware.go @@ -135,17 +135,11 @@ func NewCachingMiddleware(rc *cache.RouteCache) MiddlewareFunc { next.ServeHTTP(w, r) return } - resp, err := cache.Handler(w, r, rc, next) + err := cache.Handler(w, r, rc, next) if err != nil { - log.Errorf("could not handle request with the cache processor: %v", err) + log.Errorf("error encountered in the caching middleware: %v", err) return } - for k, h := range resp.Header { - w.Header().Set(k, h[0]) - } - if i, err := w.Write(resp.Bytes); err != nil { - log.Errorf("could not Write cache processor result into Response %d: %v", i, err) - } }) } }