go渲染静态html引擎模版

写个小例子介绍一下渲染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
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追逐梦想之路_随笔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值