- Go Web Development Cookbook
- Arpit Aggarwal
- 236字
- 2021-08-27 19:01:16
How to do it…
In this recipe, we are going to create a first-template.html with a couple of placeholders whose value will be injected by the template engine at runtime. Perform the following steps:
- Create first-template.html inside the templates directory by executing the following Unix command:
$ mkdir templates && cd templates && touch first-template.html
- Copy the following content to first-template.html:
<html>
<head>
<meta charset="utf-8">
<title>First Template</title>
<link rel="stylesheet" href="/static/stylesheets/main.css">
</head>
<body>
<h1>Hello {{.Name}}!</h1>
Your Id is {{.Id}}
</body>
</html>
The preceding template has two placeholders, {{.Name}} and {{.Id}}, whose values will be substituted or injected by the template engine at runtime.
- Create first-template.go, where we will populate the values for the placeholders, generate an HTML as an output, and write it to the client, as follows:
import
(
"fmt"
"html/template"
"log"
"net/http"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
)
type Person struct
{
Id string
Name string
}
func renderTemplate(w http.ResponseWriter, r *http.Request)
{
person := Person{Id: "1", Name: "Foo"}
parsedTemplate, _ := template.ParseFiles("templates/
first-template.html")
err := parsedTemplate.Execute(w, person)
if err != nil
{
log.Printf("Error occurred while executing the template
or writing its output : ", err)
return
}
}
func main()
{
http.HandleFunc("/", renderTemplate)
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
With everything in place, the directory structure should look like the following:

- Run the program with the following command:
$ go run first-template.go
推薦閱讀
- 通信網(wǎng)絡(luò)基礎(chǔ)與設(shè)備
- 6G潛在關(guān)鍵技術(shù)(下冊)
- Building E-commerce Sites with VirtueMart Cookbook
- 面向云平臺的物聯(lián)網(wǎng)多源異構(gòu)信息融合方法
- 中小型局域網(wǎng)組建、管理與維護實戰(zhàn)
- 企業(yè)網(wǎng)絡(luò)安全管理
- Yii Application Development Cookbook(Second Edition)
- Spring 5.0 Projects
- 通信十年:擁抱互聯(lián)網(wǎng)
- 物聯(lián)網(wǎng)頂層設(shè)計與關(guān)鍵技術(shù)
- Learning Node.js Development
- Practical Web Penetration Testing
- 數(shù)據(jù)血緣分析原理與實踐
- Selenium WebDriver 3 Practical Guide
- Cisco無線局域網(wǎng)配置基礎(chǔ)