Golang框架Gin入门实战–(8)Gin中间件详解 路由中间件 全局中间件 路由分组中间件
根据上篇文章进行修改 只把修改过的文件进行展示 没修改过的跟之上一篇一样 目录结构
main.go
代码语言:javascript复制package main
import (
"GINDEMO/routers"
"fmt"
"html/template"
"time"
"github.com/gin-gonic/gin"
)
func UnixToTime(timestamp int) string {
fmt.Println(timestamp)
t := time.Unix(int64(timestamp), 0)
return t.Format("2006-01-02 15:04:05")
}
func main() {
//创建一个默认的路由引擎
r := gin.Default()
//自定义模板函数 注意要把这个函数放在加载模板前
r.SetFuncMap(template.FuncMap{
"UnixToTime": UnixToTime,
})
//加载模板
r.LoadHTMLGlob("templates/**/*")
//配置静态web目录
r.Static("/xxx", "./static")
routers.AdminRoutersInit(r)
routers.ApiRoutersInit(r)
routers.DefaultRoutersInit(r)
// }
r.Run()
}
GINDEMOmiddlewaresinit.go
代码语言:javascript复制package middlewares
import (
"fmt"
"time"
"github.com/gin-gonic/gin"
)
func InitMiddleware(c *gin.Context) {
//判断用户是否登录
fmt.Println(time.Now())
fmt.Println(c.Request.URL)
c.Set("username", "张三")
//定义一个goroutine统计日志
cCp := c.Copy()
go func() {
time.Sleep(2 * time.Second)
fmt.Println("Done! in path" cCp.Request.URL.Path)
}()
}
GINDEMOroutersadminRouters.go
代码语言:javascript复制package routers
import (
"GINDEMO/controllers/admin"
"GINDEMO/middlewares"
"github.com/gin-gonic/gin"
)
func AdminRoutersInit(r *gin.Engine) {
//middlewares.InitMiddleware中间件
adminRouters := r.Group("/admin", middlewares.InitMiddleware)
{
adminRouters.GET("/", admin.IndexController{}.Index)
adminRouters.GET("/user", admin.UserController{}.Index)
adminRouters.GET("/user/add", admin.UserController{}.Add)
adminRouters.GET("/user/edit", admin.UserController{}.Edit)
adminRouters.GET("/article", admin.ArticleController{}.Index)
adminRouters.GET("/article/add", admin.ArticleController{}.Add)
adminRouters.GET("/article/edit", admin.ArticleController{}.Edit)
}
}
GINDEMOcontrollersadminindexController.go
代码语言:javascript复制package admin
import (
"fmt"
"github.com/gin-gonic/gin"
)
type IndexController struct {
}
func (con IndexController) Index(c *gin.Context) {
username, _ := c.Get("username")
fmt.Println(username)
v, ok := username.(string)
if ok {
c.String(200, "用户列表--" v)
} else {
c.String(200, "用户列表--获取用户失败")
}
}