81 lines
1.5 KiB
Go
81 lines
1.5 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"embed"
|
|
"fmt"
|
|
"io"
|
|
"io/fs"
|
|
"log"
|
|
"net/http"
|
|
"path/filepath"
|
|
"text/template"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
)
|
|
|
|
var FrontendFiles embed.FS
|
|
|
|
func getFileContent() string {
|
|
content, err := FrontendFiles.ReadFile("frontend/index.html")
|
|
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
return string(content)
|
|
}
|
|
|
|
func getIndex(c echo.Context) error {
|
|
IndexTemplate := template.Must(template.New("index").Parse(getFileContent()))
|
|
|
|
var tpl bytes.Buffer
|
|
IndexTemplate.Execute(&tpl, Config.Template)
|
|
|
|
return c.HTML(http.StatusOK, tpl.String())
|
|
}
|
|
|
|
func getFileSystem() http.FileSystem {
|
|
fsys, err := fs.Sub(FrontendFiles, "frontend")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
return http.FS(fsys)
|
|
}
|
|
|
|
type Template struct {
|
|
templates *template.Template
|
|
}
|
|
|
|
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
|
|
return t.templates.ExecuteTemplate(w, name, data)
|
|
}
|
|
|
|
var t *template.Template
|
|
|
|
func ServeTemplate(c echo.Context) error {
|
|
filename := filepath.Base(c.Request().URL.Path)
|
|
if filename == "/" {
|
|
filename = "index.html"
|
|
}
|
|
fmt.Println(filename)
|
|
|
|
var tpl bytes.Buffer
|
|
t.ExecuteTemplate(&tpl, filename, Config.Template)
|
|
return c.HTML(http.StatusOK, tpl.String())
|
|
}
|
|
|
|
func StartTemplating(e *echo.Echo) {
|
|
// register templates as renderer
|
|
t = template.Must(template.ParseFS(
|
|
FrontendFiles,
|
|
"frontend/templates/*",
|
|
))
|
|
fmt.Println(t.ParseName)
|
|
|
|
e.GET("/*", ServeTemplate)
|
|
staticHandler := http.FileServer(getFileSystem())
|
|
e.GET("/static/*", echo.WrapHandler(http.StripPrefix("/", staticHandler)))
|
|
}
|