From f31f7a4cc05495e378e2ab5d65c32ce5f40f9be4 Mon Sep 17 00:00:00 2001 From: xing Date: Sun, 5 Feb 2023 21:29:09 +0800 Subject: [PATCH] =?UTF-8?q?=E9=9D=99=E6=80=81=E6=96=87=E4=BB=B6=E7=BC=93?= =?UTF-8?q?=E5=AD=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config.example.yaml | 2 ++ internal/middleware/staticFileCache.go | 17 ++++++++++++++--- internal/pkg/config/config.go | 1 + 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/config.example.yaml b/config.example.yaml index 64d9631..63fd54a 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -28,6 +28,8 @@ ssl: key: "" cacheTime: + # 静态资源缓存时间Cache-Control + cacheControl: 5d # 最近文章缓存时间 recentPostCacheTime: 5m # 分类缓存时间 diff --git a/internal/middleware/staticFileCache.go b/internal/middleware/staticFileCache.go index 9d3bdc2..9ada8e2 100644 --- a/internal/middleware/staticFileCache.go +++ b/internal/middleware/staticFileCache.go @@ -1,15 +1,26 @@ package middleware import ( - "github.com/fthvgb1/wp-go/helper/slice" + "fmt" + "github.com/fthvgb1/wp-go/internal/pkg/config" "github.com/gin-gonic/gin" "strings" ) +var path = map[string]struct{}{ + "includes": {}, + "wp-content": {}, + "favicon.ico": {}, +} + func SetStaticFileCache(c *gin.Context) { f := strings.Split(strings.TrimLeft(c.FullPath(), "/"), "/") - if len(f) > 0 && slice.IsContained(f[0], []string{"wp-includes", "wp-content", "favicon.ico"}) { - c.Header("Cache-Control", "private, max-age=86400") + if _, ok := path[f[0]]; ok { + t := config.GetConfig().CacheTime.CacheControl + if t > 0 { + c.Header("Cache-Control", fmt.Sprintf("private, max-age=%d", int(t.Seconds()))) + } } + c.Next() } diff --git a/internal/pkg/config/config.go b/internal/pkg/config/config.go index 81c30a1..5901c6a 100644 --- a/internal/pkg/config/config.go +++ b/internal/pkg/config/config.go @@ -34,6 +34,7 @@ type Config struct { } type CacheTime struct { + CacheControl time.Duration `yaml:"cacheControl"` RecentPostCacheTime time.Duration `yaml:"recentPostCacheTime"` CategoryCacheTime time.Duration `yaml:"categoryCacheTime"` ArchiveCacheTime time.Duration `yaml:"archiveCacheTime"`