700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Go语言初识应用--容联云发送短信验证码 手机号注册

Go语言初识应用--容联云发送短信验证码 手机号注册

时间:2022-02-25 00:03:04

相关推荐

Go语言初识应用--容联云发送短信验证码 手机号注册

使用gin框架、gorm映射

所使用的连接容联云参考容联云官方文档,放置到utils中,

gin项目结构根据自身需要,大题如下设置:

utils--sms.go

package mainimport ("/cloopen/go-sms-sdk/cloopen""log")func main() {cfg := cloopen.DefaultConfig().// 开发者主账号,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKENWithAPIAccount("accountSId").// 主账号令牌 TOKEN,登陆云通讯网站后,可在控制台首页看到开发者主账号ACCOUNT SID和主账号令牌AUTH TOKENWithAPIToken("auth token")sms := cloopen.NewJsonClient(cfg).SMS()// 下发包体参数input := &cloopen.SendRequest{// 应用的APPIDAppId: "appId",// 手机号码To: "1352*******",// 模版IDTemplateId: "templateId",// 模版变量内容 非必填Datas: []string{"您的验证码是****"},}// 下发resp, err := sms.Send(input)if err != nil {log.Fatal(err)return}log.Printf("Response MsgId: %s \n", resp.TemplateSMS.SmsMessageSid)}

controller--user_controller.go

package controllerimport ("fmt""/gin-gonic/gin""myproject/model""myproject/utils""regexp""strconv")// 总路由分发func UserRegister(userGrp *gin.RouterGroup) {userGrp.Use().POST("/send_code", Sendcode)userGrp.Use().POST("/register", Register)}// 发送短信验证码func Sendcode(c *gin.Context) {//获取参数。手机号//验证合法//从redis获取存在则不能重复发//不存在 生成随机数 调用发短信接口//存入redis返回结果mobile := c.Query("mobile")fmt.Println(">>>>>>>" + mobile)reg := "^1[3-9]{1}\\d{9}$"result := regexp.MustCompile(reg)flag := result.MatchString(mobile)if !flag {c.JSON(200, gin.H{"code": "10011","res": "手机号不正确,请重新输入",})} else {r := utils.GetRedis()value := r.Get(mobile)if value == "" {// 生成随机值短信验证码num := utils.RandInt(10000, 99999)fmt.Println(num)num1 := strconv.Itoa(num) // 转换string// 调用容联云发送短信接口utils.SendSms(mobile, num1)r.Setex(mobile, 60, num1)c.JSON(200, gin.H{"code": "200","res": "发送成功",})} else {c.JSON(200, gin.H{"code": "10012","res": "不能重复发送",})}}}type UserInfo struct {Mobile stringCode string}// 注册 发送短信 随机值func Register(c *gin.Context) {//mobile := c.PostForm("mobile")//newcode := c.PostForm("newcode")var userInfo UserInfoc.Bind(&userInfo)mobile := userInfo.Mobilenewcode := userInfo.Coder := utils.GetRedis()code := r.Get(mobile)if code != newcode {c.JSON(200, gin.H{"code": "10020","res": "验证码不正确",})} else {//加入数据库user := &model.User{Name:mobile,Mobile: mobile,Password: "123456",}db := model.GetDb()db.Create(user)fmt.Println(user.ID)//生成token返回token, _ := utils.ReleaseToken(user.ID)c.JSON(200, gin.H{"code": "200","res": "注册成功","userid": user.ID,"token": token,})}}

获取前端传参方式:

获取 URL (query)参数

querystring指的是URL中?后面携带的参数,例如:/user/search?username=zhangsan&address=北京

获取 Form参数

前端请求的数据通过form表单提交

参数绑定

使用 Bind() 方法, 根据请求方式,自动提取 JSON, form表单 和 Query 类型的参数,放入结构体中

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。