/
app_handler.go
93 lines (78 loc) · 2.24 KB
/
app_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
91
92
93
package server
import (
"crypto/md5"
"fmt"
binHtml "html"
"net/http"
"strings"
"gopkg.in/workanator/vuego.v1/app/session"
"gopkg.in/workanator/vuego.v1/html"
)
func (server *Server) handleApp(w http.ResponseWriter, r *http.Request, sess *session.Session, tpl []byte) error {
// Get the screen
screen, err := server.bundle.Routes.Route(sess, "")
if err != nil {
return err
}
// Render application parts
var (
headHtml string
bodyHtml string
modelsHtml string
)
if screen != nil {
// Render headers form the screen and add a meta tag with screen name
if len(screen.Id) > 0 {
headHtml += `<meta name="vuego:screen:id" content="` + binHtml.EscapeString(screen.Id) + `"/>`
}
if len(screen.Name) > 0 {
headHtml = `<meta name="vuego:screen:name" content="` + binHtml.EscapeString(screen.Name) + `"/>`
}
if screen.Head != nil {
if markup, err := screen.Head.Markup(); err != nil {
return err
} else {
headHtml += "\n" + markup
}
}
// Render body
if screen.Body != nil {
if bodyEl, err := screen.Body.Render(nil, html.Rect{}); err != nil {
return err
} else if bodyEl != nil {
if markup, err := bodyEl.Markup(); err != nil {
return err
} else {
bodyHtml = markup
}
}
}
// Render models in a script tag. Each model is put in a map and has a unique identifier
// made from the screen name and the position of the model in the slice.
if len(screen.Models) > 0 {
modelsHtml = "<script>let Model = {};"
for i, m := range screen.Models {
if markup, err := m.Markup(); err != nil {
return err
} else {
key := fmt.Sprintf("%s.%04d", screen.Name, i)
encodedKey := fmt.Sprintf("%x", md5.Sum([]byte(key)))
modelsHtml += "\n"
modelsHtml += "Model['" + encodedKey + "']=" + markup + ";"
}
}
modelsHtml += "</script>"
}
}
// Process the template
body := string(tpl)
body = strings.Replace(body, "#TITLE#", screen.Title, -1)
body = strings.Replace(body, "#HEAD#", headHtml, -1)
body = strings.Replace(body, "#BODY#", bodyHtml, -1)
body = strings.Replace(body, "#MODEL#", modelsHtml, -1)
// Write the response
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(body))
return nil
}