gin框架的使用(五)——整理代码之router和response

  1. router路由
    在gin-demo目录下建立router/router.go
    在这里插入图片描述
    router.go
package router

import (
	"gin-demo/controller"
	"github.com/gin-gonic/gin"
)

func InitRouter(r *gin.Engine) *gin.Engine{
	//注册
	r.POST("/user/register",controller.Register)
	//登录
	r.POST("/user/login",controller.Login)

	return r
}

然后main.go

package main

import (
	"gin-demo/common"
	"gin-demo/router"
	"github.com/gin-gonic/gin"
)

func main(){
	r := gin.Default()
	common.InitDB()

	//创建DB实例进行数据库操作
	db := common.GetDB()
	//延迟关闭数据库
	defer db.Close();
	/*
	r.GET("/ping",func(c *gin.Context){
		c.JSON(http.StatusOK,gin.H{
			"code":200,
			"msg":"pong",
		})
	})
	r.POST("/user/register",controller.Register)
	r.POST("/user/login",controller.Login)*/
	r = router.InitRouter(r)
	r.Run(":8888")
}

然后go run main.go 看到终端显示
在这里插入图片描述
这样就成功了。不放心可以用postman测试一下。

  1. response
    在gin-demo目录下创建response/response.go
    在这里插入图片描述
package response

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

// Response 封装返回的代码
func Response(c *gin.Context,httpStatus,code int,msg string,data gin.H)  {
	c.JSON(httpStatus,gin.H{"code":code,"msg":msg,"data":data})
}

// Success 成功时返回的代码
func Success(c *gin.Context,data gin.H,msg string){
	Response(c,http.StatusOK,200,msg,data)
}


然后将登录和注册的代码c.JSON的全部改一下

// Register 用户注册
func Register(c *gin.Context){
	// 获取db
	db := common.GetDB()

	reqUser := model.User{}
	c.Bind(&reqUser)

	username := reqUser.Username
	mobile := reqUser.Mobile
	password := reqUser.Password

	//开始数据验证(简单验证)
	if len(mobile) != 11 {
		/*
		c.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"手机号不为11位",
		})*/
		response.Response(c,http.StatusUnprocessableEntity,422,"手机号应为11位",gin.H{})
		return
	}
	//密码验证
	if len(password) < 6 {
		/*
		c.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"密码必须大于6位",
		})*/
		response.Response(c,http.StatusUnprocessableEntity,422,"密码必须大于6位",gin.H{})
		return
	}
	//如果用户名为空,生成随机字符串
	if len(username) == 0 {
		username = RandomString(10)
	}

	//判断手机号是否存在
	if isMobileExist(db,mobile){
		/*
		c.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"当前手机号已经注册",
		})*/
		response.Response(c,http.StatusUnprocessableEntity,422,"当前手机号已经注册",gin.H{})
		return
	}
	//然后对密码进行加密
	hashPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		/*
		c.JSON(http.StatusUnprocessableEntity, gin.H{
			"code": 500,
			"msg":  "加密错误",
		})*/
		response.Response(c,http.StatusUnprocessableEntity,422,"加密错误",gin.H{})
		return
	}
	newUser := &model.User{
		Username:username,
		Password: string(hashPassword),
		Mobile: mobile,
	}
	db.Create(newUser)
	/*
	c.JSON(http.StatusOK,gin.H{
		"code":200,
		"msg":"注册成功",
	})*/
	response.Success(c,gin.H{},"注册成功")
}

// Login 用户的登录接口
func Login(c *gin.Context){
	db := common.GetDB()
	var reqUser model.User
	c.Bind(&reqUser)

	mobile := reqUser.Mobile
	password := reqUser.Password

	var user model.User
	//查询数据
	db.Where("mobile = ?", mobile).First(&user)
	if user.ID == 0 {
		/*
		c.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"用户不存在",
		})*/
		response.Response(c,http.StatusUnprocessableEntity,422,"用户不存在",gin.H{})
		return
	}
	//密码的对比
	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
		/*c.JSON(http.StatusUnprocessableEntity,gin.H{
			"code":422,
			"msg":"密码错误",
		})*/
		response.Response(c,http.StatusUnprocessableEntity,422,"用户不存在",gin.H{})
		return
	}
	/*
	c.JSON(http.StatusOK,gin.H{
		"code":200,
		"msg":"登录成功",
		"data":user,
	})*/
	response.Success(c,gin.H{"user":user},"登录成功")
}

然后在gin-demo下创建util/util.go
将创建随机字符串的方法放在util.go中
在这里插入图片描述

// RandomString 生成随机字符串
func RandomString(n int) string {
	var letters = []byte("abcdefghijklmnopqlstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789_")
	result := make([]byte, n)
	rand.Seed(time.Now().Unix())
	for i := range result {
		result[i] = letters[rand.Intn(len(letters))]

	}
	return string(result)

}

然后将注册那里改为

if len(username) == 0 {
		username = util.RandomString(10)
}

这里就结束了,然后接下来是viper读取配置。
慢慢学习。加油

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值