写个小例子介绍一下渲染html引擎模板的使用,大致目录结果如下:
templates目录下三个html内容如下:
index.html
<title>模板1</title>
<link rel="stylesheet" href="/css/index.css" />
<h1 class="text">三亚旅游景点1</h1>
<img src="/img/sy1.jpg" alt="" />
index2.html
<title>模板2</title>
<link rel="stylesheet" href="/css/index2.css" />
<h1 class="text">三亚旅游景点2</h1>
<img src="/img/sy2.jpg" alt="" />
index3.html
<title>模板3</title>
<link rel="stylesheet" href="/css/index3.css" />
<h1 class="text">三亚旅游景点3</h1>
<img src="/img/sy3.jpg" alt="" />
wwwroot目录下css/*.css,分别内容如下:
index.css
.text {
position: absolute;
top: 50px;
left: 100px;
color: red;
font-weight: 800;
font-size: 40px;
}
img {
width: 100%;
height: 100%;
}
index2.css
.text {
position: absolute;
top: 50px;
left: 100px;
color: rgb(166, 255, 0);
font-weight: 800;
font-size: 40px;
}
img {
width: 100%;
height: 100%;
}
index3.css
.text {
position: absolute;
top: 50px;
left: 100px;
color: rgb(0, 153, 255);
font-weight: 800;
font-size: 40px;
}
img {
width: 100%;
height: 100%;
}
wwwroot目录下img/*.jpg,分别三个图片:
sy1.jpg sy2.jpg sy3.jpg
main.go处理基本路由切换
package main
import (
"fmt"
"log"
"net/http"
"text/template"
)
func loadTemplates() *template.Template {
result := template.New("templates")
// 这两行可以合成一行代码
// res, err := result.ParseGlob("template/*.html")
// template.Must(res, err)
// 出错就终止程序
template.Must(result.ParseGlob("templates/*.html"))
return result
}
func main() {
temp := loadTemplates()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// 把路径的*.html切片
fileName := r.URL.Path[1:]
fmt.Println(fileName, "当前渲染模版")
// 设置默认值
if fileName == "" {
fileName = "index.html"
}
// 匹配html模板解析
t := temp.Lookup(fileName)
if t != nil {
err := t.Execute(w, nil)
if err != nil {
log.Fatalln(err.Error())
}
} else {
// 404
w.WriteHeader(http.StatusNotFound) // 404 Not Found
}
})
// 处理姿态资源css和img 根目录是example
http.Handle("/css/", http.FileServer(http.Dir("wwwroot")))
http.Handle("/img/", http.FileServer(http.Dir("wwwroot")))
// 启动服务器
server := http.Server{
Addr: "localhost:9999",
}
server.ListenAndServe()
}
服务启动http://localhost:9999/ 或者 http://localhost:9999/index.html 访问效果如下:
http://localhost:9999/index2.html
http://localhost:9999/index3.html