I wrote this Go Lang code for serving web page with template and values passed to parameters through Go program
// +build
package main
import (
"html/template"
"io/ioutil"
"net/http"
)
type Blog struct {
title string
heading string
para string
}
func loadfile(filename string) (string, error) {
byte, err := ioutil.ReadFile(filename)
return string(byte), err
}
func handler(w http.ResponseWriter, r *http.Request) {
blog := Blog{title: "GoLang", heading: "WebServer", para: "coding"}
t, err := template.ParseFiles("test.html")
fmt.Println(err)
t.Execute(w, blog)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":9000", nil)
}
HTML Template file named as test.html as follows
<html>
<head>
<title>{{.title}}</title>
</head>
<body>
<h1>{{.heading}}</h1>
<p>{{.para}}</p>
</body>
</html>
When I execute the program, the issue is that the page served is coming up as blank. The parameters that were to be passed to the template don't show up on the page rendered. I even printed the error but there is no error
You should write the first letter of the fields of Blog
with upper case to make them public
type Blog struct {
Title string
Heading string
Para string
}
Also you can pass a map to the method Execute()
, something like this:
b := map[string]string{
"title": "GoLang",
"heading": "WebServer",
"para": "coding",
}
t.Execute(w, b)