Go Web Development Cookbook
上QQ阅读APP看书,第一时间看更新

How it works…

Once we run the program, the HTTP server will start locally listening on port 8080.

Browsing http://localhost:8080 will show us the Hello Foo! served by the template engine, as shown in the following screenshot:

Execute curl -X GET http://localhost:8080 from the command line as:

$ curl -X GET http://localhost:8080

This will result in the following response from the server:

Let's understand the Go program we have written:

  • type Person struct { Id string Name string }: Here we define a person struct type that has Id and Name fields.

The field name should begin with a capital letter in the type definition; otherwise, it will result in errors and will not be replaced in the template.

Next, we defined a renderTemplate() handler, which does a lot of things.

  • person := Person{Id: "1", Name: "Foo"}: Here we are initializing a person struct type with Id as 1 and Name as Foo.
  • parsedTemplate, _ := template.ParseFiles("templates/first-template.html"): Here we are calling ParseFiles of the html/template package, which creates a new template and parses the filename we pass as an input, which is first-template.html ,in a templates directory. The resulting template will have the name and contents of the input file.
  • err := parsedTemplate.Execute(w, person): Here we are calling an Execute handler on a parsed template, which injects person data into the template, generates an HTML output, and writes it onto an HTTP response stream.
  • if err != nil {log.Printf("Error occurred while executing the template or writing its output : ", err) return }: Here we check whether there are any problems while executing the template or writing its output on the response stream. If there are, then we log the error and exit with a status code of 1.