Embed templates and static files

This commit is contained in:
Maximilian Friedersdorff 2025-06-25 22:43:34 +01:00
parent 868d2a7bbd
commit 8edd857d22
11 changed files with 31 additions and 17 deletions

6
Makefile Normal file
View file

@ -0,0 +1,6 @@
all: build
build:
go run cmd/fetch-static/main.go
go build cmd/server/main.go

7
cmd/fetch-static/main.go Normal file
View file

@ -0,0 +1,7 @@
package main
import "forgejo.gwairfelin.com/max/gonotes/internal/conf"
func main() {
conf.FetchAssets()
}

View file

@ -27,8 +27,8 @@ func main() {
"/static/",
logger(
http.StripPrefix(
"/static",
http.FileServer(http.Dir(conf.Conf.Static.Dir)),
"/static/",
http.FileServer(http.FS(conf.Static)),
),
),
)

View file

@ -3,8 +3,5 @@ notesdir = "/var/lib/gonotes/saved_notes"
address = ":8080"
protocol = "tcp"
[templates]
dir = "/usr/share/gonotes/templates"
[static]
dir = "/var/www/gonotes/static"

View file

@ -1,6 +1,7 @@
package conf
import (
"embed"
"errors"
"io"
"log"
@ -17,7 +18,7 @@ type Asset struct {
Url string
}
func (asset *Asset) FetchIfNotExists(staticPath string) {
func (asset *Asset) fetchIfNotExists(staticPath string) {
destPath := filepath.Join(staticPath, asset.Path)
err := os.MkdirAll(path.Dir(destPath), os.FileMode(0750))
@ -57,12 +58,8 @@ type Config struct {
Protocol string
Extension string
NotesDir string
Templates struct {
Dir string
}
Static struct {
Dir string
Root string
}
}
@ -75,6 +72,10 @@ var (
{Path: "icons/eye.svg", Url: "https://raw.githubusercontent.com/twbs/icons/refs/heads/main/icons/eye.svg"},
}
BaseTemplate string = "base.tmpl.html"
//go:embed static/*
Static embed.FS
//go:embed templates/*
Templates embed.FS
)
func LoadConfig(path string) {
@ -89,8 +90,10 @@ func LoadConfig(path string) {
if err != nil {
log.Fatal(err)
}
}
func FetchAssets() {
for _, asset := range assets {
asset.FetchIfNotExists(Conf.Static.Dir)
asset.fetchIfNotExists("./internal/conf/static")
}
}

0
internal/conf/static/.gitignore vendored Normal file
View file

View file

@ -3,7 +3,6 @@ package templ
import (
"html/template"
"net/http"
"os"
"path/filepath"
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
@ -13,17 +12,19 @@ type Ctx map[string]any
func RenderTemplate(w http.ResponseWriter, tmpl string, context any) error {
files := []string{
filepath.Join(conf.Conf.Templates.Dir, conf.BaseTemplate),
filepath.Join(conf.Conf.Templates.Dir, tmpl),
filepath.Join("templates", "base.tmpl.html"),
filepath.Join("templates", tmpl),
}
for _, f := range files {
_, err := os.Stat(f)
file, err := conf.Templates.Open(f)
if err != nil {
return err
}
file.Close()
}
t, err := template.ParseFiles(files...)
t, err := template.ParseFS(conf.Templates, files...)
t.ExecuteTemplate(w, "base", context)
return err
}