Skip to content

Commit 58a3190

Browse files
authored
fix: logging and cache middleware (#72)
* Fix logging and cache middleware * linter * minor fix * linter * fixes * Enhanced cache config * linter * minor change * update comment
1 parent 070ffcb commit 58a3190

File tree

5 files changed

+86
-31
lines changed

5 files changed

+86
-31
lines changed

pkg/zrouter/zmiddlewares/cache.go

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"github.com/zondax/golem/pkg/zcache"
77
"github.com/zondax/golem/pkg/zrouter/domain"
88
"net/http"
9+
"regexp"
910
"runtime/debug"
1011
"time"
1112
)
@@ -14,23 +15,32 @@ const (
1415
cacheKeyPrefix = "zrouter_cache"
1516
)
1617

18+
type CacheProcessedPath struct {
19+
Regex *regexp.Regexp
20+
TTL time.Duration
21+
}
22+
1723
func CacheMiddleware(cache zcache.ZCache, config domain.CacheConfig) func(next http.Handler) http.Handler {
24+
processedPaths := processCachePaths(config.Paths)
25+
1826
return func(next http.Handler) http.Handler {
1927
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2028
path := r.URL.Path
2129
fullURL := constructFullURL(r)
2230

23-
if ttl, found := config.Paths[path]; found {
24-
key := constructCacheKey(fullURL)
31+
for _, pPath := range processedPaths {
32+
if pPath.Regex.MatchString(path) {
33+
key := constructCacheKey(fullURL)
2534

26-
if tryServeFromCache(w, r, cache, key) {
35+
if tryServeFromCache(w, r, cache, key) {
36+
return
37+
}
38+
39+
rw := &responseWriter{ResponseWriter: w}
40+
next.ServeHTTP(rw, r) // Important: this line needs to be BEFORE setting the cache.
41+
cacheResponseIfNeeded(rw, r, cache, key, pPath.TTL)
2742
return
2843
}
29-
30-
rw := &responseWriter{ResponseWriter: w}
31-
next.ServeHTTP(rw, r) // Important: This line needs to be BEFORE setting the cache.
32-
cacheResponseIfNeeded(rw, r, cache, key, ttl)
33-
return
3444
}
3545

3646
next.ServeHTTP(w, r)
@@ -89,3 +99,14 @@ func ParseCacheConfigPaths(paths map[string]string) (domain.CacheConfig, error)
8999

90100
return domain.CacheConfig{Paths: parsedPaths}, nil
91101
}
102+
103+
func processCachePaths(paths map[string]time.Duration) []CacheProcessedPath {
104+
var processedPaths []CacheProcessedPath
105+
for path, ttl := range paths {
106+
processedPaths = append(processedPaths, CacheProcessedPath{
107+
Regex: PathToRegexp(path),
108+
TTL: ttl,
109+
})
110+
}
111+
return processedPaths
112+
}

pkg/zrouter/zmiddlewares/common.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package zmiddlewares
2+
3+
import (
4+
"regexp"
5+
"strings"
6+
)
7+
8+
func PathToRegexp(path string) *regexp.Regexp {
9+
escapedPath := regexp.QuoteMeta(path)
10+
escapedPath = strings.ReplaceAll(escapedPath, "\\{", "{")
11+
escapedPath = strings.ReplaceAll(escapedPath, "\\}", "}")
12+
13+
pattern := regexp.MustCompile(`\{[^}]*\}`).ReplaceAllString(escapedPath, "[^/]+")
14+
return regexp.MustCompile("^" + pattern + "$")
15+
}

pkg/zrouter/zmiddlewares/http.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,6 @@ func requestIDMiddleware(next http.Handler) http.Handler {
3333
})
3434
}
3535

36-
func Logger() Middleware {
37-
return LoggingMiddleware
36+
func Logger(options LoggingMiddlewareOptions) Middleware {
37+
return LoggingMiddleware(options)
3838
}

pkg/zrouter/zmiddlewares/logging.go

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,32 +4,52 @@ import (
44
"bytes"
55
"github.com/zondax/golem/pkg/logger"
66
"net/http"
7+
"regexp"
78
"time"
89
)
910

10-
func LoggingMiddleware(next http.Handler) http.Handler {
11-
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
12-
buffer := &bytes.Buffer{}
11+
type LoggingMiddlewareOptions struct {
12+
ExcludePaths []string
13+
}
14+
15+
func LoggingMiddleware(options LoggingMiddlewareOptions) func(http.Handler) http.Handler {
16+
excludeRegexps := make([]*regexp.Regexp, len(options.ExcludePaths))
17+
for i, path := range options.ExcludePaths {
18+
excludeRegexps[i] = PathToRegexp(path)
19+
}
20+
21+
return func(next http.Handler) http.Handler {
22+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
23+
requestPath := r.URL.Path
24+
for _, re := range excludeRegexps {
25+
if re.MatchString(requestPath) {
26+
next.ServeHTTP(w, r)
27+
return
28+
}
29+
}
30+
31+
buffer := &bytes.Buffer{}
1332

14-
rw := &responseWriter{
15-
ResponseWriter: w,
16-
body: buffer,
17-
}
33+
rw := &responseWriter{
34+
ResponseWriter: w,
35+
body: buffer,
36+
}
1837

19-
start := time.Now()
20-
next.ServeHTTP(rw, r)
21-
duration := time.Since(start)
22-
ctx := r.Context()
38+
start := time.Now()
39+
next.ServeHTTP(rw, r)
40+
duration := time.Since(start)
41+
ctx := r.Context()
2342

24-
log := logger.GetLoggerFromContext(ctx)
43+
log := logger.GetLoggerFromContext(ctx)
2544

26-
if log.IsDebugEnabled() {
27-
log.Debugf("Method: %s - URL: %s | Status: %d - Duration: %s - Response Body: %s",
28-
r.Method, r.URL.String(), rw.status, duration, string(rw.Body()))
29-
return
30-
}
45+
if log.IsDebugEnabled() {
46+
log.Debugf("Method: %s - URL: %s | Status: %d - Duration: %s - Response Body: %s",
47+
r.Method, r.URL.String(), rw.status, duration, string(rw.Body()))
48+
return
49+
}
3150

32-
log.Infof("Method: %s - URL: %s | Status: %d - Duration: %s",
33-
r.Method, r.URL.String(), rw.status, duration)
34-
})
51+
log.Infof("Method: %s - URL: %s | Status: %d - Duration: %s",
52+
r.Method, r.URL.String(), rw.status, duration)
53+
})
54+
}
3555
}

pkg/zrouter/zrouter.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,6 @@ func (r *zrouter) SetDefaultMiddlewares() {
100100

101101
r.Use(zmiddlewares.RequestMetrics(r.appName, r.metricsServer))
102102
r.Use(zmiddlewares.RequestID())
103-
r.Use(zmiddlewares.Logger())
104103
}
105104

106105
func (r *zrouter) Group(prefix string) Routes {

0 commit comments

Comments
 (0)