vanity/server/router/templates.go

60 lines
1.1 KiB
Go
Raw Normal View History

package router
import (
"embed"
"html/template"
"io/fs"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"go.jolheiser.com/overlay"
)
var (
//go:embed templates
templateFS embed.FS
ofs = overlay.MustNew(customRoot(), templateFS)
Version string
)
func customRoot() string {
bin, err := os.Executable()
if err != nil {
bin = ""
}
customPath := os.Getenv("VANITY_CUSTOM")
if customPath == "" {
customPath = filepath.Join(bin, "custom")
}
return customPath
}
func tmpl(domain, name string) (*template.Template, error) {
return template.New(name).Funcs(funcMap(domain)).ParseFS(ofs, "templates/base.tmpl", "templates/"+name)
}
func static() http.Handler {
sub, err := fs.Sub(ofs, "templates/static")
if err != nil {
return nil
}
return http.FileServer(http.FS(sub))
}
func funcMap(domain string) template.FuncMap {
return template.FuncMap{
"AppVer": func() string {
return Version
},
"GoVer": func() string {
return runtime.Version()
},
"Domain": func() string {
return strings.TrimSuffix(domain, "/")
},
}
}