diff --git a/go.mod b/go.mod index 1fb38e3..80b8141 100644 --- a/go.mod +++ b/go.mod @@ -1,4 +1,4 @@ -module github.com/gin-contrib/static +module github.com/ghezzofr/static require ( github.com/elazarl/go-bindata-assetfs v1.0.0 diff --git a/static.go b/static.go index ffa00ee..3895080 100644 --- a/static.go +++ b/static.go @@ -1,6 +1,7 @@ package static import ( + "fmt" "net/http" "os" "path" @@ -22,6 +23,12 @@ type localFileSystem struct { indexes bool } +type CacheConfigs struct { + Public bool + MaxAge uint + Immutable bool +} + func LocalFile(root string, indexes bool) *localFileSystem { return &localFileSystem{ FileSystem: gin.Dir(root, indexes), @@ -55,16 +62,40 @@ func ServeRoot(urlPrefix, root string) gin.HandlerFunc { return Serve(urlPrefix, LocalFile(root, false)) } -// Static returns a middleware handler that serves static files in the given directory. -func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc { +// GenericServe returns a middleware handler that serves static files in the given directory. +func GenericServe(urlPrefix string, fs ServeFileSystem, cc CacheConfigs) gin.HandlerFunc { fileserver := http.FileServer(fs) if urlPrefix != "" { fileserver = http.StripPrefix(urlPrefix, fileserver) } return func(c *gin.Context) { if fs.Exists(urlPrefix, c.Request.URL.Path) { + var cacheControl []string + if cc.Public { + cacheControl = append(cacheControl, "public") + } + if cc.MaxAge != 0 { + cacheControl = append(cacheControl, fmt.Sprintf("max-age=%d", cc.MaxAge)) + } else { + cacheControl = append(cacheControl, "no-store") + } + if cc.Immutable { + cacheControl = append(cacheControl, "immutable") + } + c.Writer.Header().Add("Cache-Control", strings.Join(cacheControl, ", ")) fileserver.ServeHTTP(c.Writer, c.Request) c.Abort() } } } + +// Static returns a middleware handler that serves static files in the given directory. +func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc { + return GenericServe(urlPrefix, fs, CacheConfigs{MaxAge: 0}) +} + +// ServeCached returns a middleware handler that similar as Serve but with the Cache-Control Header set as passed in the cacheAge parameter +func ServeCached(urlPrefix string, fs ServeFileSystem, cc CacheConfigs) gin.HandlerFunc { + return GenericServe(urlPrefix, fs, cc) + +} diff --git a/static_test.go b/static_test.go index 6925005..1e446f5 100644 --- a/static_test.go +++ b/static_test.go @@ -132,3 +132,24 @@ func TestListIndex(t *testing.T) { w = performRequest(router, "GET", "/") assert.Contains(t, w.Body.String(), `