Cache javascripts in browser

This commit is contained in:
0xJacky 2022-03-07 17:30:45 +08:00
parent 7d6b979dad
commit 77dfd64445
5 changed files with 101 additions and 65 deletions

View file

@ -7,7 +7,7 @@ tmp_dir = "tmp"
[build]
# Just plain old shell command. You could use `make` as well.
cmd = "go build -o ./tmp/main ."
cmd = "go build -ldflags=\"-X 'github.com/0xJacky/Nginx-UI/server/settings.BuildTime=$(date +%Y.%m.%d.%H%M%S)'\" -o ./tmp/main ."
# Binary file yields from `cmd`.
bin = "tmp/main"
# Customize binary.

View file

@ -151,7 +151,7 @@ jobs:
- name: Build
run: |
mkdir -p dist
go build -ldflags "$LD_FLAGS" -o dist/nginx-ui -v main.go
go build -ldflags "$LD_FLAGS -X 'github.com/0xJacky/Nginx-UI/server/settings.BuildTime=$(date +%Y.%m.%d.%H%M%S)'" -o dist/nginx-ui -v main.go
- name: Archive backend artifacts
uses: actions/upload-artifact@v2

View file

@ -4,14 +4,29 @@ import (
"encoding/base64"
"github.com/0xJacky/Nginx-UI/frontend"
"github.com/0xJacky/Nginx-UI/server/model"
"github.com/0xJacky/Nginx-UI/server/settings"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"io/fs"
"log"
"net/http"
"path"
"strings"
"time"
)
func recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if err := recover(); err != nil {
log.Println(err)
}
}()
c.Next()
}
}
func authRequired() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
@ -64,3 +79,18 @@ func mustFS(dir string) (serverFileSystem static.ServeFileSystem) {
return
}
func cacheJs() gin.HandlerFunc {
return func(c *gin.Context) {
if strings.Contains(c.Request.URL.String(), "js") {
c.Header("Cache-Control", "max-age: 1296000")
t, _ := time.Parse("2006.01.02.150405", settings.BuildTime)
t = t.Add(-8 * time.Hour)
lastModified := strings.ReplaceAll(t.Format(time.RFC1123), "UTC", "GMT")
if c.Request.Header.Get("If-Modified-Since") == lastModified {
c.AbortWithStatus(http.StatusNotModified)
}
c.Header("Last-Modified", lastModified)
}
}
}

View file

@ -14,7 +14,9 @@ func InitRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(recovery())
r.Use(cacheJs())
r.Use(static.Serve("/", mustFS("")))

View file

@ -7,6 +7,10 @@ import (
var Conf *ini.File
var (
BuildTime string
)
type Server struct {
HttpPort string
RunMode string