43 lines
783 B
Go
43 lines
783 B
Go
|
package static
|
||
|
|
||
|
import (
|
||
|
"embed"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"html/template"
|
||
|
"io/fs"
|
||
|
"net/http"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
var (
|
||
|
//go:embed assets
|
||
|
assetsFs embed.FS
|
||
|
|
||
|
//go:embed view
|
||
|
viewFs embed.FS
|
||
|
)
|
||
|
|
||
|
func LoadStatic(engine *gin.Engine) {
|
||
|
sub, err := fs.Sub(assetsFs, "assets")
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
|
cacheSuffix := []string{".css", ".js", ".js.map", ".css.map"}
|
||
|
|
||
|
engine.Use(func(ctx *gin.Context) {
|
||
|
if ctx.Request.Method == http.MethodGet {
|
||
|
for _, suffix := range cacheSuffix {
|
||
|
if strings.HasSuffix(ctx.Request.URL.Path, suffix) {
|
||
|
ctx.Writer.Header().Set("Cache-Control", "max-age=7200")
|
||
|
break
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
ctx.Next()
|
||
|
})
|
||
|
|
||
|
engine.StaticFS("/assets", http.FS(sub))
|
||
|
engine.SetHTMLTemplate(template.Must(template.New("").ParseFS(viewFs, "view/*")))
|
||
|
}
|