Skip to content

Commit

Permalink
beatlabs#128 make middleware cache abstraction more concrete
Browse files Browse the repository at this point in the history
Signed-off-by: Vangelis Katikaridis <[email protected]>
  • Loading branch information
drakos74 committed May 9, 2020
1 parent 8de7e51 commit 6527324
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 10 deletions.
15 changes: 13 additions & 2 deletions component/http/cache/route_cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cache
import (
"bytes"
"errors"
"fmt"
"net/http"
"time"

Expand Down Expand Up @@ -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
Expand Down
10 changes: 2 additions & 8 deletions component/http/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
})
}
}
Expand Down

0 comments on commit 6527324

Please sign in to comment.