2

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

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks you so much. I didn't know that non-capital makes the variable private. So just a question on this - if the variables of struct are private, we can only use them in the functions that struct ?
If the field is private will be visible only at package scope, in your example it will be accessible in any file inside the main package, but because t.Execute() is in other pkg will not be able to access the fields. That's the way to do encapsulation in Go private: lower case, public: upper case

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.