implemented embed.FS for templates and static files

This commit is contained in:
BroodjeAap 2022-12-18 11:08:10 +00:00
parent 806fcda019
commit af44423453
2 changed files with 25 additions and 11 deletions

34
main.go
View file

@ -1,12 +1,14 @@
package main package main
import ( import (
"embed"
"encoding/json" "encoding/json"
"fmt" "fmt"
"html/template"
"io/fs"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
"path/filepath"
"strconv" "strconv"
"strings" "strings"
@ -21,11 +23,12 @@ import (
"gorm.io/gorm" "gorm.io/gorm"
"broodjeaap.net/go-watch/notifiers" "broodjeaap.net/go-watch/notifiers"
_ "embed"
) )
var baseHTML = filepath.Join("templates", "base.html") //go:embed templates static
var indexHTML = filepath.Join("templates", "index.html") var EMBED_FS embed.FS
var newWatchHTML = filepath.Join("templates", "newWatch.html")
type Web struct { type Web struct {
router *gin.Engine router *gin.Engine
@ -83,7 +86,11 @@ func (web *Web) initDB() {
func (web *Web) initRouter() { func (web *Web) initRouter() {
web.router = gin.Default() web.router = gin.Default()
web.router.Static("/static", "./static") staticFS, err := fs.Sub(EMBED_FS, "static")
if err != nil {
log.Fatalln("Could not load static embed fs")
}
web.router.StaticFS("/static", http.FS(staticFS))
web.initTemplates() web.initTemplates()
web.router.HTMLRender = web.templates web.router.HTMLRender = web.templates
@ -106,13 +113,20 @@ func (web *Web) initRouter() {
func (web *Web) initTemplates() { func (web *Web) initTemplates() {
web.templates = multitemplate.NewRenderer() web.templates = multitemplate.NewRenderer()
web.templates.AddFromFiles("index", "templates/base.html", "templates/index.html")
web.templates.AddFromFiles("watchView", "templates/base.html", "templates/watch/view.html")
web.templates.AddFromFiles("watchEdit", "templates/base.html", "templates/watch/edit.html")
web.templates.AddFromFiles("cacheView", "templates/base.html", "templates/cache/view.html") templatesFS, err := fs.Sub(EMBED_FS, "templates")
if err != nil {
log.Fatalln("Could not load templates embed fs")
}
web.templates.AddFromFiles("500", "templates/base.html", "templates/500.html") web.templates.Add("index", template.Must(template.ParseFS(templatesFS, "base.html", "index.html")))
web.templates.Add("watchView", template.Must(template.ParseFS(templatesFS, "base.html", "watch/view.html")))
web.templates.Add("watchEdit", template.Must(template.ParseFS(templatesFS, "base.html", "watch/edit.html")))
web.templates.Add("cacheView", template.Must(template.ParseFS(templatesFS, "base.html", "cache/view.html")))
web.templates.Add("500", template.Must(template.ParseFS(templatesFS, "base.html", "500.html")))
} }
func (web *Web) initCronJobs() { func (web *Web) initCronJobs() {

View file

@ -7,6 +7,6 @@
- twitter? - twitter?
- sms? - sms?
- etch? - etch?
- implement embed.FS - ~~implement embed.FS~~
- change docker builds - change docker builds
- trusted proxies in conf? - trusted proxies in conf?