go语言使用gin框架

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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值