三十五、Gin注册功能实战

目录

一、创建请求组

二、service下创建register.go文件

三、实现密码加密功能

四、在register方法中使用encryptPassword函数


一、创建请求组

复制代码
const (
	rootPath   = "/api/"
	noAuthPath = "/out/api/"
)

	//创建请求组
	noAuth := r.Group(noAuthPath)
	//注册功能路由绑定
	noAuth.POST("cms/register", cmsApp.Register)

二、service下创建register.go文件

复制代码
package services

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)
//入参校验
type RegisterReq struct {
	UserID   string `json:"user_id" binding:"required"`
	Password string `json:"password" binding:"required"`
	Nickname string `json:"nickname" binding:"required"`
}
//返回校验
type RegisterRsp struct {
	Message string `json:"message" binding:"required"`
}

func (c *CmsApp) Register(ctx *gin.Context) {
	var req RegisterReq
    //当入参时错误返回
	if err := ctx.ShouldBindJSON(&req); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	//todo 密码加密
	//todo 账号校验是否存在
	//todo 保存
    
    //入参没有错误时返回
	ctx.JSON(http.StatusOK, gin.H{
		"msg":  "ok",
		"code": http.StatusOK,
		"data": RegisterRsp{
			Message: fmt.Sprintf("注册成功"),
		},
	})
}

三、实现密码加密功能

使用

复制代码
bcrypt.GenerateFromPassword 进行密码加密,完成encryptPassword函数
复制代码
func encryptPassword(password string) (string, error) {
	//因为GenerateFromPassword(password []byte, cost int) ([]byte, error) {
	//入参为byte所以要把password转化一下
	//cost 一般用默认10 这里的越大计算的复杂度就越高
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	if err != nil {
		fmt.Printf("bcrypt failed, err:%v\n", err)
	}
	//再转回string返回
	return string(hashedPassword), nil
}

四、在register方法中使用encryptPassword函数

复制代码
//todo 密码加密
	hashedPassword, err := encryptPassword(req.Password)
	if err != nil {
		ctx.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
	}
	fmt.Printf("this is hashedPassword %v", hashedPassword)

打印结果:

复制代码
$2a$10$4jvJs03CwJLXbHWhCeCWOuiwVk/PR3aEb771iJoPTF3hLQBXwTdqe

若多次打印会发现结果是不一样的

相关推荐
yesyesido4 小时前
智能文件格式转换器:文本/Excel与CSV无缝互转的在线工具
开发语言·python·excel
_200_4 小时前
Lua 流程控制
开发语言·junit·lua
环黄金线HHJX.4 小时前
拼音字母量子编程PQLAiQt架构”这一概念。结合上下文《QuantumTuan ⇆ QT:Qt》
开发语言·人工智能·qt·编辑器·量子计算
王夏奇4 小时前
python在汽车电子行业中的应用1-基础知识概念
开发语言·python·汽车
He_Donglin4 小时前
Python图书爬虫
开发语言·爬虫·python
qq_256247054 小时前
除了“温度”,如何用 Penalty (惩罚) 治好 AI 的“复读机”毛病?
后端
星融元asterfusion4 小时前
AsterNOS SONiC基于YANG模型的现代网络管理:从CLI到gNMI的演进
开发语言·sonic·yang
web3.08889994 小时前
1688商品详情API接口深度解析
开发语言·python
内存不泄露4 小时前
基于Spring Boot和Vue 3的智能心理健康咨询平台设计与实现
vue.js·spring boot·后端
qq_12498707534 小时前
基于Spring Boot的电影票网上购票系统的设计与实现(源码+论文+部署+安装)
java·大数据·spring boot·后端·spring·毕业设计·计算机毕业设计