本文已参与「新人创作礼」活动,一起开启掘金创作之路.
1、model概述
如果我们有一个功能想在多个控制器、或者多个模板里面复用的话,那么我们就可以把公共的功能单独抽取出来作为一个模块(Model)。 Model 是逐步抽象的过程,一般我们会在Model 里面封装一些公共的方法让不同 控制器 使用,也可以在 Model 中实现和数据库交互。
2、Model 里面封装公共的方法
1、新建 models/ publicTools.go
```go package models import ( "crypto/md5" "fmt" "time" "github.com/astaxie/beego" ) //时间戳间戳转换成日期 func UnixToDate(timestamp int) string { t := time.Unix(int64(timestamp), 0)
return t.Format("2022-05-21 10:02:01") //只是转换的一个模板
}
//日期转换成时间戳 func DateToUnix(str string) int64 {
template := "2022-05-21 10:02:01"
t, err := time.ParseInLocation(template, str, time.Local)
if err != nil {
return 0
}
return t.Unix()
} //返回时间戳 func GetUnix() int64 { return time.Now().Unix() } //返回日期 func GetDate() string { template := "2022-05-21 10:02:01" return time.Now().Format(template) } //返回年月日 func GetDay() string { template := "20220521" return time.Now().Format(template) } //公共md5加密方法 func Md5(str string) string { data := []byte(str) return fmt.Sprintf("%x\n", md5.Sum(data)) } 2、创建完公共方法的model,就可以引入到控制器中了。
go package controllers
import ( "ginProject/models" ) day := models.GetDay() ```
3、调用 Model 注册全局模板函数
* 注意*:注册模板函数需要在加载模板之上。
go r := gin.Default() r.SetFuncMap(template.FuncMap{ "unixToDate": models.UnixToDate, })
然后,我们就可以在控制器中使用了!!!!
go func (c UserController) Add(ctx *gin.Context) { ctx.HTML(http.StatusOK, "admin/user/add.html", gin.H{ "now": models.GetUnix(), }) }
在前端html中,我们就可一直接使用{{.now | unixToData}}来渲染数据了
html 当前时间:<h5>{{.now | unixToDate}}</h5> // .now为控制器中key-vlaue中传的,因为使用的是自定义模板,所以应该使用自定义模板中的unixToDate。
4、、Golang Md5 加密
golang 包对应的网站:https://pkg.go.dev/ ,打开之后搜索 md5就能看到一些关于MD5的包
方法一: go data := []byte("abc") //转换为二进制数据 has := md5.Sum(data) //加密成密文 md5str := fmt.Sprintf("%x", has) //转换为string fmt.Println(md5str) //打印
方法二:
go h := md5.New() io.WriteString(h, "abc") //io方法输出string类型的密文 fmt.Printf("%x\n", h.Sum(nil))