0
点赞
收藏
分享

微信扫一扫

【Gin框架】自定义 Model


阅读目录

  • ​​源码​​
  • ​​E:\gormlearn\gin\magin.go​​
  • ​​E:\gormlearn\gin\routers\defaultRouters.go​​
  • ​​E:\gormlearn\gin\controllers\wgchen\defaultController.go​​
  • ​​E:\gormlearn\gin\templates\default\index.html​​
  • ​​E:\gormlearn\gin\go.mod​​
  • ​​预览​​

源码

gin
|-- controllers
| `-- wgchen
| `-- defaultController.go
|-- go.mod
|-- go.sum
|-- magin.go
|-- models
| `-- tools.go
|-- routers
| `-- defaultRouters.go
`-- templates
`-- default
`-- index.html

下载并安装 gin 框架:​​go get -u github.com/gin-gonic/gin​​。

E:\gormlearn\gin\magin.go

package main

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

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

func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// 自定义模板函数 注意要把这个函数放在加载模板前
r.SetFuncMap(template.FuncMap{
"UnixToTime": models.UnixToTime,
})
//加载模板 放在配置路由前面
r.LoadHTMLGlob("templates/**/*")

// 路由文件
routers.DefaultRoutersInit(r)

// 启动 HTTP 服务,默认在 0.0.0.0:8080 启动服务
r.Run(":8080")
}

E:\gormlearn\gin\routers\defaultRouters.go

路由文件

package routers

import (
"wgchen/controllers/wgchen"

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

func DefaultRoutersInit(r *gin.Engine) {
defaultRouters := r.Group("/")
{
defaultRouters.GET("/", wgchen.DefaultController{}.Index)
}
}

E:\gormlearn\gin\controllers\wgchen\defaultController.go

控制器

import (
"net/http"

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

type DefaultController struct{}

func (con DefaultController) Index(c *gin.Context) {
// fmt.Println(models.UnixToTime(16297885654))
c.HTML(http.StatusOK, "default/index.html", gin.H{
"msg": "我是神",
"t": 1629788418,
})
}

E:\gormlearn\gin\templates\default\index.html

<!-- 相当于给模版定义一个名字 define end 成对出现 -->
{{ define "default/index.html" }}

default 页 <br/>
{{.msg}} <br/>
{{UnixToTime .t}}


{{ end }}

E:\gormlearn\gin\go.mod

module wgchen

go 1.19

require (
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.8.2 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.0 // indirect
github.com/go-playground/validator/v10 v10.11.1 // indirect
github.com/goccy/go-json v0.10.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/leodido/go-urn v1.2.1 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/ugorji/go/codec v1.2.8 // indirect
golang.org/x/crypto v0.5.0 // indirect
golang.org/x/net v0.5.0 // indirect
golang.org/x/sys v0.4.0 // indirect
golang.org/x/text v0.6.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)

预览

【Gin框架】自定义 Model_gin


【Gin框架】自定义 Model_gin_02


举报

相关推荐

0 条评论