官术网_书友最值得收藏!

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.
主站蜘蛛池模板: 洛宁县| 遵化市| 曲沃县| 河间市| 股票| 上林县| 栾城县| 永兴县| 彭水| 孟州市| 永平县| 隆尧县| 宁都县| 古浪县| 玛多县| 龙井市| 湘潭市| 西畴县| 肥城市| 鹤山市| 普陀区| 舒城县| 句容市| 明溪县| 治县。| 石城县| 卢龙县| 白河县| 洛隆县| 曲靖市| 汨罗市| 海宁市| 吉木萨尔县| 吐鲁番市| 简阳市| 开鲁县| 克什克腾旗| 化德县| 甘泉县| 原阳县| 吴忠市|