mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2025-10-28 12:45:47 +00:00
feat: add http cache for static files (#395)
* feat: add http cache for static files fix #392 * minor typo fix
This commit is contained in:
@@ -1,10 +1,12 @@
|
|||||||
package middleware
|
package middleware
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
"tinyauth/internal/assets"
|
"tinyauth/internal/assets"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
@@ -27,14 +29,16 @@ func (m *UIMiddleware) Init() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
m.uiFs = ui
|
m.uiFs = ui
|
||||||
m.uiFileServer = http.FileServer(http.FS(ui))
|
m.uiFileServer = http.FileServerFS(ui)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (m *UIMiddleware) Middleware() gin.HandlerFunc {
|
func (m *UIMiddleware) Middleware() gin.HandlerFunc {
|
||||||
return func(c *gin.Context) {
|
return func(c *gin.Context) {
|
||||||
switch strings.Split(c.Request.URL.Path, "/")[1] {
|
path := strings.TrimPrefix(c.Request.URL.Path, "/")
|
||||||
|
|
||||||
|
switch strings.SplitN(path, "/", 2)[0] {
|
||||||
case "api":
|
case "api":
|
||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
@@ -42,12 +46,19 @@ func (m *UIMiddleware) Middleware() gin.HandlerFunc {
|
|||||||
c.Next()
|
c.Next()
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
_, err := fs.Stat(m.uiFs, strings.TrimPrefix(c.Request.URL.Path, "/"))
|
_, err := fs.Stat(m.uiFs, path)
|
||||||
|
|
||||||
|
// Enough for one authentication flow
|
||||||
|
maxAge := 15 * time.Minute
|
||||||
|
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
c.Request.URL.Path = "/"
|
c.Request.URL.Path = "/"
|
||||||
|
} else if strings.HasPrefix(path, "assets/") {
|
||||||
|
// assets are named with a hash and can be cached for a long time
|
||||||
|
maxAge = 30 * 24 * time.Hour
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.Writer.Header().Set("Cache-Control", fmt.Sprintf("public, max-age=%d", int(maxAge.Seconds())))
|
||||||
m.uiFileServer.ServeHTTP(c.Writer, c.Request)
|
m.uiFileServer.ServeHTTP(c.Writer, c.Request)
|
||||||
c.Abort()
|
c.Abort()
|
||||||
return
|
return
|
||||||
|
|||||||
Reference in New Issue
Block a user