Files
gin-contrib/static/serve.go
T
2024-04-02 15:13:13 +03:00

43 lines
1.1 KiB
Go

package static
import (
"fmt"
"net/http"
"git.company.lan/gopkg/gin"
)
type Override func(*gin.Context) bool
type ServeFileSystem interface {
http.FileSystem
Exists(prefix string, path string) bool
Override(*gin.Context) bool
}
func ServeRoot(urlPrefix, root string) gin.HandlerFunc {
return Serve(urlPrefix, LocalFile(root, false))
}
// Serve returns a middleware handler that serves static files in the given directory.
func Serve(urlPrefix string, fs ServeFileSystem) gin.HandlerFunc {
return ServeCached(urlPrefix, fs, 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, cacheAge uint) 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) && !fs.Override(c) {
if cacheAge != 0 {
c.Writer.Header().Add("Cache-Control", fmt.Sprintf("max-age=%d", cacheAge))
}
fileserver.ServeHTTP(c.Writer, c.Request)
c.Abort()
}
}
}