1.修改之前的接口路由文件
package mainimport ("fmt"//测试接口-路由ginCtrl "gin/controller"sysUtil "gin/system/util""github.com/gin-gonic/gin""log"//系统基础功能接口--路由sysCtrl "gin/system/controller"
)func main() {apiV1 := gin.Default()exploreRouter := apiV1.Group("/api")//没有数据库交互的接口//r := gin.Default()exploreRouter.GET("/get", func(ctx *gin.Context) {ctx.String(200 /*http.StatusOK*/, "hello word golang-web!")})exploreRouter.POST("/user/post", func(ctx *gin.Context) {ctx.String(200, "这是一个post请求!")})exploreRouter.PUT("/user/put", func(ctx *gin.Context) {ctx.String(200, "这是一个put请求!")})exploreRouter.DELETE("/user/delete", func(ctx *gin.Context) {ctx.String(200, "这是一个delete请求!")})//有数据库交互的接口get请求 返回jsonexploreRouter.GET("/getJson", ginCtrl.GetUserInfo)get请求 返回json 接口传参exploreRouter.GET("/getJson/:id", ginCtrl.GetUserInfo)POST请求 返回json 接口传参jsonexploreRouter.POST("/postJson", ginCtrl.PostUserInfo)异常捕获exploreRouter.GET("/getErr", ginCtrl.GetDb)异常捕获exploreRouter.GET("/getDb", ginCtrl.GetDb)//TODO -------------------------------------system系统功能模块接口路由-登录相关接口----------------------------------//1.登录验证返回token 接口白名单,不校验是否携带tokenexploreRouter.POST("/login", sysCtrl.Login)//2密码生成exploreRouter.POST("/rsapassword", sysCtrl.Rsapassword)//TODO -------------------------------------system系统功能模块接口路由-用户操作相关接口----------------------------------//TODO JWT 拦截、验证token 参考 https://blog.csdn.net/ic_xcc/article/details/120433968exploreRouter.Use(sysUtil.AuthMiddleware())//token验证中间件{//POST请求 db操作,新增数据exploreRouter.POST("/addDb", sysCtrl.SaveUser)//GET请求 db操作,按id查询数据exploreRouter.GET("/getByIdDb", sysCtrl.GetUserById)//GET请求 db操作,查询数据exploreRouter.GET("/getByUserList", sysCtrl.GetByUserList)//GET请求 db多表orm操作,查询数据exploreRouter.GET("/getByUserJoinList", sysCtrl.GetByUserJoinList)}// 设置 release模式//gin.SetMode(gin.ReleaseMode)// 或者 设置debug模式gin.SetMode(gin.DebugMode)err := apiV1.Run(":9999")if err != nil {log.Fatalln("服务启动失败,原因:", err)} else {fmt.Println("服务启动成功,后端接口请访问 127.0.0.1:9999")}
}
2. JWT 的TOKEN认证
package utilimport ("fmt""gin/common"sysentity "gin/system/entity""github.com/dgrijalva/jwt-go""github.com/gin-gonic/gin""net/http"
)// ParseJwtToken 解析token得到是自己创建的Claims
func ParseJwtToken(jwtToken string) (*sysentity.JwtClaims, error) {var secretKey = []byte("login_user_key")var jwtclaim = &sysentity.JwtClaims{}fmt.Println("ParseJwtToken=========================TOKEN:-----------"+jwtToken)_, err := jwt.ParseWithClaims(jwtToken, jwtclaim, func(*jwt.Token) (interface{}, error) {//得到盐return secretKey/*sysentity.Secret*/, nil})if err != nil {if ve, ok := err.(*jwt.ValidationError); ok {if ve.Errors&jwt.ValidationErrorMalformed != 0 {return nil, sysentity.TokenMalformed} else if ve.Errors&jwt.ValidationErrorExpired != 0 {// Token is expiredreturn nil, sysentity.TokenExpired} else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 {return nil, sysentity.TokenNotValidYet} else {return nil, sysentity.TokenInvalid}}}else {fmt.Println("ParseJwtToken==========================解析没有错误")}return jwtclaim, nil
}//token校验
// 校验token中间件
func AuthMiddleware() gin.HandlerFunc {// var tokeString = ""//var c *gin.Contextreturn func(c *gin.Context) {// 从请求头中获取tokentokeString := c.GetHeader("Token")fmt.Println("==================================请求头中的token为:" + tokeString)if tokeString == "" {c.JSON(http.StatusOK, gin.H{"code": 405,"message": "必须传递token",})c.Abort()return}claims, err := ParseJwtToken(tokeString)if claims == nil {common.ReturnError(c, 500, "token解析错误,请联系开发人员处理!", "", int64(len("")))panic("")}if err != nil {c.JSON(http.StatusOK, gin.H{"code": 1005,"message": "token解析错误",})c.Abort()//return//common.ReturnError(c, 500, "token解析错误", "", int64(len("")))}// 从token中解析出来的数据挂载到上下文上,方便后面的控制器使用fmt.Println("===============claims.UID" + claims.Uuid)//fmt.Println("===============claims.UserName" + claims.UserName)c.Set("Uuid", claims.Uuid)c.Set("UserName", claims.UserName)c.Next()}
}
3.测试