Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add serve cache and related test #15

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -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
Expand Down
35 changes: 33 additions & 2 deletions static.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package static

import (
"fmt"
"net/http"
"os"
"path"
Expand All @@ -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),
Expand Down Expand Up @@ -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)

}
21 changes: 21 additions & 0 deletions static_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,3 +132,24 @@ func TestListIndex(t *testing.T) {
w = performRequest(router, "GET", "/")
assert.Contains(t, w.Body.String(), `<a href="`+filename)
}

func TestCache(t *testing.T) {
// SETUP file
testRoot, _ := os.Getwd()
f, err := ioutil.TempFile(testRoot, "")
if err != nil {
t.Error(err)
}
defer os.Remove(f.Name())
f.WriteString("Gin Web Framework")
f.Close()

dir, filename := filepath.Split(f.Name())
router := gin.New()
router.Use(ServeCached("/", LocalFile(dir, true), 3600))

w := performRequest(router, "GET", "/"+filename)
assert.Equal(t, w.Code, 200)
assert.Equal(t, w.Header().Get("Cache-Control"), "max-age=3600")

}