Serving content generated with templates

Create the file template.tpl with the following content:

        <html>
          <body>
            Hi, I'm HTML body for index.html!
          </body>
        </html>

Create the file dynamic.go with the following content:

package main

import "net/http"
import "html/template"

func main() {
	tpl, err := template.ParseFiles("template.tpl")
	if err != nil {
		panic(err)
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		err := tpl.Execute(w, "John Doe")
		if err != nil {
			panic(err)
		}
	})
	http.ListenAndServe(":8085", nil)
}

output:

sangam:golang-daily sangam$ go run main.go
sangam:golang-daily sangam$ curl http://localhost:8085
   <html>
       <body>
         Hi, I'm HTML body for index.html!
      </body>
   </html>


How it works…