gin 目录结构
// 忽略掉依赖包目录
╰─$ tree -I vendor
.
├── debug
├── main.go
└── templates
└── index.html
main.go 主文件
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
// 加载 templates 目录下的所有文件
router.LoadHTMLGlob("templates/*")
// 或者使用这种方法加载也是OK的: router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
// 参数使用 gin.H 传入index.html中!也就是使用的是index.html模板
c.HTML(200, "index.html", gin.H{
"title": "Gin 测试模板",
})
})
// 重定向
router.GET("/vic", func(c *gin.Context) {
// c.Redirect(302, "https://www.baidu.com")
c.Redirect(302, "index")
})
router.Run(":8000")
}
index.html 模板
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Gin Document</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="main.css" />
<script src="main.js"></script>
</head>
<body>
<h1>
{{.title}}
</h1>
</body>
</html>
页面显示
// 访问
http://127.0.0.1:8000/index
// 显示
Gin 测试模板