前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Golang框架Gin入门实战--(8)Gin中间件详解 路由中间件 全局中间件 路由分组中间件

Golang框架Gin入门实战--(8)Gin中间件详解 路由中间件 全局中间件 路由分组中间件

作者头像
互联网-小阿宇
发布2022-11-21 21:43:39
8530
发布2022-11-21 21:43:39
举报
文章被收录于专栏:互联网-小阿宇互联网-小阿宇

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()
}

GINDEMO\middlewares\init.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)
	}()
}

GINDEMO\routers\adminRouters.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)
	}
}

GINDEMO\controllers\admin\indexController.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, "用户列表--获取用户失败")
	}

}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2022-06-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • Golang框架Gin入门实战–(8)Gin中间件详解 路由中间件 全局中间件 路由分组中间件
相关产品与服务
消息队列 TDMQ
消息队列 TDMQ (Tencent Distributed Message Queue)是腾讯基于 Apache Pulsar 自研的一个云原生消息中间件系列,其中包含兼容Pulsar、RabbitMQ、RocketMQ 等协议的消息队列子产品,得益于其底层计算与存储分离的架构,TDMQ 具备良好的弹性伸缩以及故障恢复能力。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档