gin框架基础用法
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/**/*") //这里是加载html文件的目录和文件,
router.GET("/p/index", func(c *gin.Context) { //这里是指定浏览器需要访问的url路径,
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{ //这里是路径对应的html模板文件.
"title": "Posts", //这里是指定html字段相同的键值信息.这里指定了,浏览器中可以机芯提取值.
})
})
router.GET("/u/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
router.Run(":8080")
}
定义一个不转移相应内容的safe模板函数
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"net/http"
)
func main() {
router := gin.Default()
router.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML {
return template.HTML(str)
},
})
router.LoadHTMLFiles("./index.tmpl") //指定文件加载路径和加载位置.
router.GET("/index", func(c *gin.Context) { //请求url名称为index.(可以自定义,)
c.HTML(http.StatusOK, "index.tmpl", "<a href='https://baidu.com'>百度</a>") //页面显示百度并且点击后会跳转到一个链接.链接地址就是前面的href指定的地址.文件是index.tmpl文件
})
router.Run(":8000")
}
同级目录下的index.tmpl文件
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>修改模板引擎的标识符</title>
</head>
<body>
<div>{{ . | safe }}</div>
</body>
</html>