diff --git a/config/main.go b/config/main.go index 3c290eb..7019647 100644 --- a/config/main.go +++ b/config/main.go @@ -18,4 +18,5 @@ type Config struct { SMTPSender string RequestsPerMinute int CacheParameter string + CacheMaxAge int } diff --git a/dist/templates/footer.html b/dist/templates/footer.html index 3617488..d4fa9ac 100644 --- a/dist/templates/footer.html +++ b/dist/templates/footer.html @@ -3,7 +3,7 @@ Fork this project on GitHub | Created by Markus Tenghamn - + {{ template "tracking.html" }} \ No newline at end of file diff --git a/docker-compose.yml b/docker-compose.yml index f1b9eb3..32e7ec1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -32,6 +32,7 @@ services: - STRICT_TRANSPORT_SECURITY=false - REQUESTS_PER_MINUTE=5 - CACHE_PARAMETER= + - CACHE_MAX_AGE= depends_on: - db ports: diff --git a/env.go b/env.go index 53a5c76..2518ee1 100644 --- a/env.go +++ b/env.go @@ -77,5 +77,16 @@ func loadEnvVariables() (c config.Config) { if os.Getenv("CACHE_PARAMETER") != "" { c.CacheParameter = os.Getenv("CACHE_PARAMETER") } + + // CacheMaxAge is how many seconds to cache static assets + c.CacheMaxAge = 31536000 + if os.Getenv("CACHE_MAX_AGE") != "" { + i, err := strconv.Atoi(os.Getenv("CACHE_MAX_AGE")) + if err != nil { + log.Fatalln(err) + return + } + c.CacheMaxAge = i + } return c } diff --git a/main.go b/main.go index 6f40c03..2940d60 100644 --- a/main.go +++ b/main.go @@ -53,7 +53,7 @@ func Run() { } assets := r.Group("/assets") - assets.Use(middleware.Cache()) + assets.Use(middleware.Cache(conf.CacheMaxAge)) assets.StaticFS("/", http.FS(subFS)) diff --git a/middleware/cache.go b/middleware/cache.go index 25bc805..306e5fc 100644 --- a/middleware/cache.go +++ b/middleware/cache.go @@ -1,10 +1,13 @@ package middleware -import "github.com/gin-gonic/gin" +import ( + "fmt" + "github.com/gin-gonic/gin" +) -func Cache() gin.HandlerFunc { +func Cache(maxAge int) gin.HandlerFunc { return func(c *gin.Context) { - c.Header("Cache-Control", "public, max-age=60") + c.Header("Cache-Control", fmt.Sprintf("public, max-age=%d", maxAge)) c.Next() } } diff --git a/middleware/throttle.go b/middleware/throttle.go index 950a78a..86d8b3f 100644 --- a/middleware/throttle.go +++ b/middleware/throttle.go @@ -5,21 +5,15 @@ import ( "github.com/ulule/limiter/v3" middlewareGin "github.com/ulule/limiter/v3/drivers/middleware/gin" "github.com/ulule/limiter/v3/drivers/store/memory" - "log" + "time" ) func Throttle(limit int) gin.HandlerFunc { - // Define a limit rate to 3 requests per minute. - rate, err := limiter.NewRateFromFormatted("5-M") - if err != nil { - log.Fatal(err) - } - store := memory.NewStore() - if err != nil { - log.Fatal(err) - } // Create a new middleware with the limiter instance. - return middlewareGin.NewMiddleware(limiter.New(store, rate)) + return middlewareGin.NewMiddleware(limiter.New(store, limiter.Rate{ + Period: time.Minute, + Limit: int64(limit), + })) }