-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathviewHandler.go
62 lines (50 loc) · 1.02 KB
/
viewHandler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"embed"
"io"
"io/fs"
"net/http"
"os"
"github.com/aymerick/raymond"
"github.com/labstack/echo/v4"
)
//go:embed views
var embeddedViewFS embed.FS
func viewFS() fs.FS {
if devMode {
return os.DirFS("views")
}
fsys, err := fs.Sub(embeddedViewFS, "views")
if err != nil {
panic(err)
}
return fsys
}
func getTemplate(view string) string {
fs := viewFS()
f, openErr := fs.Open(view)
if openErr != nil {
panic(openErr)
}
defer f.Close()
retVal, readErr := io.ReadAll(f)
if readErr != nil {
panic(readErr)
}
return string(retVal)
}
func viewHandler(view string) func(c echo.Context) error {
rawTemplate := getTemplate(view)
parsedTemplate, parseErr := raymond.Parse(rawTemplate)
if parseErr != nil {
panic(parseErr)
}
return func(c echo.Context) error {
//content := fmt.Sprintf("from %s", view)
content, execErr := parsedTemplate.Exec(nil)
if execErr != nil {
return c.String(http.StatusInternalServerError, execErr.Error())
}
return c.HTML(http.StatusOK, content)
}
}