-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrender.go
62 lines (57 loc) · 1.61 KB
/
render.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 go_ssr
import (
"encoding/json"
"fmt"
"github.com/natewong1313/go-react-ssr/internal/html"
"github.com/natewong1313/go-react-ssr/internal/utils"
"github.com/rs/zerolog"
"html/template"
"os"
"path/filepath"
"runtime"
)
// RenderConfig is the config for rendering a route
type RenderConfig struct {
File string
Title string
MetaTags map[string]string
Props interface{}
}
// RenderRoute renders a route to html
func (engine *Engine) RenderRoute(renderConfig RenderConfig) []byte {
// routeID is the program counter of the caller
pc, _, _, _ := runtime.Caller(1)
routeID := fmt.Sprint(pc)
props, err := propsToString(renderConfig.Props)
if err != nil {
return html.RenderError(err, routeID)
}
task := renderTask{
engine: engine,
logger: zerolog.New(zerolog.ConsoleWriter{Out: os.Stderr}).With().Timestamp().Logger(),
routeID: routeID,
props: props,
filePath: filepath.ToSlash(utils.GetFullFilePath(engine.Config.FrontendDir + "/" + renderConfig.File)),
config: renderConfig,
}
renderedHTML, css, js, err := task.Start()
if err != nil {
return html.RenderError(err, task.routeID)
}
return html.RenderHTMLString(html.Params{
Title: renderConfig.Title,
MetaTags: renderConfig.MetaTags,
JS: template.JS(js),
CSS: template.CSS(css),
RouteID: task.routeID,
ServerHTML: template.HTML(renderedHTML),
})
}
// Convert props to JSON string, or set to null if no props are passed
func propsToString(props interface{}) (string, error) {
if props != nil {
propsJSON, err := json.Marshal(props)
return string(propsJSON), err
}
return "null", nil
}