Responding to an HTTP Request using Templates

suggest change

Responses can be written to an http.ResponseWriter with templates. This is a handy way to create dynamic pages.

To learn about templates, see the text and HTML templates chapter.

Here is a simple example that uses html/template to respond to an HTTP request:

package main

import(
    "html/template"
    "net/http"
    "log"
)

func main(){
    http.HandleFunc("/",WelcomeHandler)
    http.ListenAndServe(":8080",nil)
}

type User struct{
    Name string
    nationality string //unexported field.
}

func check(err error){
    if err != nil{
        log.Fatal(err)
    }
}

func WelcomeHandler(w http.ResponseWriter, r *http.Request){
    if r.Method == "GET"{
        t,err := template.ParseFiles("welcomeform.html")
        check(err)
        t.Execute(w,nil)
    }else{
        r.ParseForm()
        myUser := User{}
        myUser.Name = r.Form.Get("entered_name")
        myUser.nationality = r.Form.Get("entered_nationality")
        t, err := template.ParseFiles("welcomeresponse.html")
        check(err)
        t.Execute(w,myUser)
    }
}

Where, the contents of

  1. welcomeform.html are:
<head>
    <title> Help us greet you </title>
</head>
<body>
    <form method="POST" action="/">
        Enter Name: <input type="text" name="entered_name">
        Enter Nationality: <input type="text" name="entered_nationality">
        <input type="submit" value="Greet me!">
    </form>
</body>
  1. welcomeresponse.html are:
<head>
    <title> Greetings, {{.Name}} </title>
</head>
<body>
    Greetings, {{.Name}}.<br>
    We know you are a {{.nationality}}!
</body>

Note:

  1. Make sure that the .html files are in the correct directory.
  2. After starting the server, visit http://localhost:8080/.
  3. After the form is submitted, the template cannot read the unexported nationality field. t.Execute returns that error, and this handler ignores it.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents