I am trying to fetch a website from page header (Javascript). I have successfully done this by loading from file into header.
// write file content to page
func get_content(w http.ResponseWriter, val string) {
content, err := ioutil.ReadFile("./public/tmpl/" + val + ".html")
if err != nil {
log.Fatal(err)
}
fmt.Fprint(w, string(content))
}
Using the above code can load from file and then fetch into innerHTML in Go template.
But now I want to populate the page BEFORE I send it to the client. Sort of save to memory and then to the header? This pseudo code does not work. What is the correct syntax for this? Is it possible?
func handler(w http.ResponseWriter, r *http.Request) {
//fetch json into menu variable
var menu map[string]interface{}
if err := json.Unmarshal([]byte(jsondata), &menu); err != nil {
panic(err)
}
// store in memory
var page bytes.Buffer
page.WriteString(tpl.ExecuteTemplate(w, "nav.html", menu),
//write to header - accessible from the client
fmt.Fprint(w, string(page))
}
const jsondata = `{
"main": [{
"menu_id": "1",
"menu_txt": "Home"
}, {
"menu_id": "2",
"menu_txt": "Prefs"
}],
"sub": [{
"menu_id": "3",
"menu_txt": "Test"
}, {
"menu_id": "4",
"menu_txt": "Test2"
}]
}
`
The template looks like this:
<html>
<body>
<ul>
{{ range .main }}
<li id="{{.menu_id}}">{{.menu_txt}}</li>
{{ end }}
</ul>
<ul>
{{ range .sub }}
<li id="{{.menu_id}}">{{.menu_txt}}</li>
{{ end }}
</ul>
</body>
</html>
The error I get is:
missing ‘,’ before newline in argument list