From 682584b034c7acded765d0468bf03db75ff915a9 Mon Sep 17 00:00:00 2001 From: hokamsingh Date: Fri, 30 Aug 2024 21:00:15 +0530 Subject: [PATCH] feat: tests --- .gitignore | 3 +++ go.mod | 5 +++- go.sum | 20 +++++++------- internal/core/middleware/cacher.go | 34 +++++++++--------------- internal/core/router/router.go | 5 ++-- internal/utils/utils.go | 16 +++++++++++ pkg/lessgo/less.go | 14 +++++----- tests/lessgo/framework_benchmark_test.go | 3 ++- 8 files changed, 57 insertions(+), 43 deletions(-) diff --git a/.gitignore b/.gitignore index a8d4f8f..c645c82 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,7 @@ *.dll *.so *.dylib +*.yml # Output of the go coverage tool *.out @@ -45,3 +46,5 @@ Thumbs.db # Docker files Dockerfile docker-compose.yml + +.air.toml \ No newline at end of file diff --git a/go.mod b/go.mod index c668d2c..e30ef6a 100644 --- a/go.mod +++ b/go.mod @@ -13,6 +13,9 @@ require ( ) require ( - github.com/cespare/xxhash/v2 v2.1.2 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect + github.com/stretchr/testify v1.9.0 // indirect + golang.org/x/net v0.26.0 // indirect + golang.org/x/sys v0.22.0 // indirect ) diff --git a/go.sum b/go.sum index dfd8e3c..4829852 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE= -github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= @@ -26,16 +26,16 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= -github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= go.uber.org/dig v1.18.0 h1:imUL1UiY0Mg4bqbFfsRQO5G4CGRBec/ZujWTvSVp3pw= go.uber.org/dig v1.18.0/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781 h1:DzZ89McO9/gWPsQXS/FVKAlG02ZjaQ6AlZRBimEYOd0= -golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e h1:fLOSk5Q00efkSvAm+4xcoXD+RRmLmmulPn5I3Y9F2EM= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ= +golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE= +golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI= +golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.16.0 h1:a94ExnEXNtEwYLGJSIUxnWoxoRz/ZcCsV63ROupILh4= +golang.org/x/text v0.16.0/go.mod h1:GhwF1Be+LQoKShO3cGOHzqOgRrGaYc9AvblQOmPVHnI= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= diff --git a/internal/core/middleware/cacher.go b/internal/core/middleware/cacher.go index ee62036..49c635e 100644 --- a/internal/core/middleware/cacher.go +++ b/internal/core/middleware/cacher.go @@ -18,17 +18,7 @@ type Caching struct { cacheControl bool } -func NewCaching(redisAddr string, ttl time.Duration, cacheControl bool) *Caching { - ctx := context.Background() - client := redis.NewClient(&redis.Options{ - Addr: redisAddr, // e.g., "localhost:6379" - // Username: "", - Password: "secret", - }) - _, err := client.Ping(ctx).Result() - if err != nil { - log.Fatalf("Could not connect to Redis: %v", err) - } +func NewCaching(client *redis.Client, ttl time.Duration, cacheControl bool) *Caching { return &Caching{ client: client, ttl: ttl, @@ -76,14 +66,14 @@ func (c *Caching) Handle(next http.Handler) http.Handler { } // Capture response - rec := &responseRecorder{ResponseWriter: w, statusCode: http.StatusOK, body: new(bytes.Buffer)} + rec := &ResponseRecorder{ResponseWriter: w, StatusCode: http.StatusOK, Body: new(bytes.Buffer)} next.ServeHTTP(rec, r) // Cache only successful responses (status code 200) - if r.Method == http.MethodGet && rec.statusCode == http.StatusOK { + if r.Method == http.MethodGet && rec.StatusCode == http.StatusOK { cachedResponse := cachedResponse{ Headers: rec.Header(), - Body: rec.body.String(), + Body: rec.Body.String(), } var buffer bytes.Buffer @@ -108,24 +98,24 @@ type cachedResponse struct { Body string } -type responseRecorder struct { +type ResponseRecorder struct { http.ResponseWriter - statusCode int - body *bytes.Buffer + StatusCode int + Body *bytes.Buffer } -func (rec *responseRecorder) Write(p []byte) (int, error) { - rec.body.Write(p) // Write to the buffer +func (rec *ResponseRecorder) Write(p []byte) (int, error) { + rec.Body.Write(p) // Write to the buffer return rec.ResponseWriter.Write(p) // Stream response to client } -func (rec *responseRecorder) WriteHeader(statusCode int) { - rec.statusCode = statusCode +func (rec *ResponseRecorder) WriteHeader(statusCode int) { + rec.StatusCode = statusCode rec.ResponseWriter.WriteHeader(statusCode) } // Implement the Flush method -func (rec *responseRecorder) Flush() { +func (rec *ResponseRecorder) Flush() { if flusher, ok := rec.ResponseWriter.(http.Flusher); ok { flusher.Flush() } diff --git a/internal/core/router/router.go b/internal/core/router/router.go index 5f11ffc..3c0b7fa 100644 --- a/internal/core/router/router.go +++ b/internal/core/router/router.go @@ -9,6 +9,7 @@ import ( "sync" "time" + "github.com/go-redis/redis/v8" "github.com/gorilla/mux" "github.com/hokamsingh/lessgo/internal/core/context" "github.com/hokamsingh/lessgo/internal/core/middleware" @@ -182,9 +183,9 @@ func WithJSONParser(options middleware.ParserOptions) Option { // // Note: Ensure that the Redis server is running and accessible at the specified // address. -func WithCaching(redisAddr string, ttl time.Duration, cacheControl bool) Option { +func WithCaching(client *redis.Client, ttl time.Duration, cacheControl bool) Option { return func(r *Router) { - caching := middleware.NewCaching(redisAddr, ttl, cacheControl) + caching := middleware.NewCaching(client, ttl, cacheControl) r.Use(caching) } } diff --git a/internal/utils/utils.go b/internal/utils/utils.go index 2b92892..b04bc2e 100644 --- a/internal/utils/utils.go +++ b/internal/utils/utils.go @@ -1,6 +1,7 @@ package utils import ( + "context" "crypto/rand" "encoding/hex" "errors" @@ -10,7 +11,10 @@ import ( "path/filepath" "strings" "time" + "unicode" + + "github.com/go-redis/redis/v8" ) func GetFolderPath(folderName string) (string, error) { @@ -130,3 +134,15 @@ func Assert(guard bool, text string) { panic(text) } } + +func NewRedisClient(redisAddr string) *redis.Client { + ctx := context.Background() + client := redis.NewClient(&redis.Options{ + Addr: redisAddr, // e.g., "localhost:6379" + }) + _, err := client.Ping(ctx).Result() + if err != nil { + log.Fatalf("Could not connect to Redis: %v", err) + } + return client +} diff --git a/pkg/lessgo/less.go b/pkg/lessgo/less.go index 7ba0e64..cfcf586 100644 --- a/pkg/lessgo/less.go +++ b/pkg/lessgo/less.go @@ -3,6 +3,7 @@ package LessGo import ( "time" + "github.com/go-redis/redis/v8" "github.com/hokamsingh/lessgo/internal/core/concurrency" "github.com/hokamsingh/lessgo/internal/core/config" "github.com/hokamsingh/lessgo/internal/core/context" @@ -238,8 +239,8 @@ func WithFileUpload(uploadDir string, maxFileSize int64, allowedExts []string) r // // Note: Ensure that the Redis server is running and accessible at the specified // address. -func WithCaching(redisAddr string, ttl time.Duration, cacheControl bool) router.Option { - return router.WithCaching(redisAddr, ttl, cacheControl) +func WithCaching(redisClient *redis.Client, ttl time.Duration, cacheControl bool) router.Option { + return router.WithCaching(redisClient, ttl, cacheControl) } // WithCsrf is an option function that enables CSRF protection for the router. @@ -317,11 +318,6 @@ func WithTemplateRendering(templateDir string) router.Option { return router.WithTemplateRendering(templateDir) } -// // ServeStatic creates a file server handler to serve static files -// func ServeStatic(pathPrefix, dir string) http.Handler { -// return router.ServeStatic(pathPrefix, dir) -// } - func RegisterModules(r *router.Router, modules []module.IModule) error { return di.RegisterModules(r, modules) } @@ -382,3 +378,7 @@ func ConvertToBytes(size int64, unit SizeUnit) (int64, error) { s, err := utils.ConvertToBytes(float64(size), utils.SizeUnit(unit)) return int64(s), err } + +func NewRedisClient(redisAddr string) *redis.Client { + return utils.NewRedisClient(redisAddr) +} diff --git a/tests/lessgo/framework_benchmark_test.go b/tests/lessgo/framework_benchmark_test.go index 5b0005b..a1c158c 100644 --- a/tests/lessgo/framework_benchmark_test.go +++ b/tests/lessgo/framework_benchmark_test.go @@ -22,13 +22,14 @@ func BenchmarkHandler(b *testing.B) { size, _ := LessGo.ConvertToBytes(int64(1024), LessGo.Kilobytes) parserOptions := LessGo.NewParserOptions(size * 5) + rClient := LessGo.NewRedisClient("localhost:6379") App := LessGo.App( LessGo.WithCORS(*corsOptions), LessGo.WithJSONParser(*parserOptions), LessGo.WithCookieParser(), LessGo.WithCsrf(), LessGo.WithXss(), - LessGo.WithCaching("redis:6379", 5*time.Minute, true), + LessGo.WithCaching(rClient, 5*time.Minute, true), ) // Add a simple /ping route