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

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.
主站蜘蛛池模板: 苏尼特左旗| 新龙县| 大同市| 平定县| 灵川县| 西丰县| 新竹县| 永昌县| 桐庐县| 天气| 夏河县| 祁门县| 合水县| 枣强县| 阜南县| 乐山市| 绩溪县| 博野县| 黄陵县| 皋兰县| 孟州市| 大新县| 宜兰市| 康保县| 辽中县| 富裕县| 江阴市| 黄梅县| 遵义市| 申扎县| 灵丘县| 精河县| 徐水县| 平遥县| 赫章县| 祁阳县| 丹棱县| 伊川县| 博爱县| 教育| 甘肃省|