关于 Model

如果我们的应用非常简单的话,我们可以在 Controller 里面处理常见的业务逻辑。但是如果我们 有一个功能想在多个控制器、或者多个模板里面复用 的话,那么我们就可以把公共的功能单独抽取出来作为一个模块(Model)

封装一个 Model

新建 models/tools.go,并在里面实现一个Unix时间戳转日期时间的功能

1
2
3
4
5
6
7
8
9
10
package models

import (
"time"
)

func UnixToDate(timestamp int) string {
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05")
}

调用 Model

在控制器中调用

\controllers\admin\adminController.go为例

1
2
3
4
func (c AdminController) Index(con *gin.Context) {
date := models.UnixToDate(1646554975)
con.String(200, "转换后的日期和时间是:"+date)
}

在模板文件中调用

注意顺序,注册模板函数需要在加载模板上面

main.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package main

import (
"html/template"
"test/models"
"test/routers"

"github.com/gin-gonic/gin"
)

func main() {

r := gin.Default()

r.SetFuncMap(template.FuncMap{
"unixToDate": models.UnixToDate,
})

r.LoadHTMLGlob("templates/**/*")

//前台路由
routers.DefaultRoutersInit(r)
//后台路由
routers.AdminRoutersInit(r)
//api 路由
routers.ApiRoutersInit(r)

r.Run()
}

\controllers\admin\adminController.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package admin

import (
"github.com/gin-gonic/gin"
)

type AdminController struct {
BaseController
}

func (c AdminController) Index(con *gin.Context) {
con.HTML(200, "admin/index.html", gin.H{
"now": 1646554975,
})
}

func (c AdminController) User(con *gin.Context) {
username, _ := con.Get("username")
con.String(200, username.(string))
}

func (c AdminController) Article(con *gin.Context) {
con.String(200, "新闻列表")
}

\templates\admin\index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{{ define "admin/index.html" }}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>{{.now | unixToDate}}</h2>
</body>
</html>

{{ end }}