-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpage-view-handler.go
90 lines (76 loc) · 2.01 KB
/
page-view-handler.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package hardwire
import (
"net/http"
echo "github.com/labstack/echo/v4"
config "github.com/ncpa0/hardwire/configuration"
hw "github.com/ncpa0/hardwire/hw-context"
"github.com/ncpa0/hardwire/utils"
"github.com/ncpa0/hardwire/views"
)
type View interface {
Render(hwContext hw.HardwireContext, c echo.Context) (*views.RenderedView, error)
}
func createResponse(c echo.Context, view View) error {
ifNoneMatch := c.Request().Header.Get("If-None-Match")
renderResult, err := view.Render(HardwireContext, c)
if err != nil {
return utils.HandleError(c, err)
}
if renderResult.Etag != "" && ifNoneMatch == renderResult.Etag {
return c.NoContent(http.StatusNotModified)
}
if renderResult.Etag != "" {
c.Response().Header().Set("ETag", renderResult.Etag)
}
return c.HTML(http.StatusOK, "<!DOCTYPE html>\n"+renderResult.Html)
}
func createPageViewHandler(view *views.PageView, conf *config.Configuration) func(c echo.Context) error {
if view.Metadata.ShouldRedirect {
return func(c echo.Context) error {
err := c.Redirect(http.StatusMovedPermanently, view.Metadata.RedirectURL)
if err != nil {
return err
}
if conf.BeforeResponse != nil {
return conf.BeforeResponse(c)
}
return nil
}
}
return func(c echo.Context) error {
selector := c.Request().Header.Get("HX-Target")
c.Response().Header().Set("Vary", "HX-Target")
if !view.IsDynamic() {
c.Response().Header().Set(
"Cache-Control",
config.GenerateCacheHeaderForStaticRoute(),
)
} else {
c.Response().Header().Set(
"Cache-Control",
config.GenerateCacheHeaderForDynamicRoute(),
)
}
if selector != "" {
child := view.QuerySelector("#" + selector)
if !child.IsNil() {
err := createResponse(c, child.Get())
if err != nil {
return err
}
if conf.BeforeResponse != nil {
return conf.BeforeResponse(c)
}
return nil
}
}
err := createResponse(c, view)
if err != nil {
return err
}
if conf.BeforeResponse != nil {
return conf.BeforeResponse(c)
}
return nil
}
}