1. 调用的时序图
2. 安装redis
因为短息验证码是存在redis服务中,所以需要安装redis,redis的安装比较简单可以自行安装即可。
3. 启动redis
4. 监听端口代码
package main
import (
"fmt"
"log"
"net/http"
"src/login"
)
func main() {
fmt.Println("server start")
http.HandleFunc("/login", loginByPassword)
// 获取验证码
http.HandleFunc("/getPhoneCode", getPhoneCode)
// 校验验证码
http.HandleFunc("/checkCode", checkCode)
if err := http.ListenAndServe(":8888", nil); err != nil{
log.Fatal("Server error", err)
}
fmt.Println("server out")
}
func loginByPassword(w http.ResponseWriter, r *http.Request) {
login.Login(w, r)
}
func getPhoneCode(w http.ResponseWriter, r *http.Request) {
login.GetPhoneCode(w, r)
}
func checkCode(w http.ResponseWriter, r *http.Request) {
login.CheckCode(w, r)
}
5. 获取验证码及调用短息服务
// 获取手机号验证码
func GetPhoneCode(w http.ResponseWriter, r *http.Request) {
var result pojo.Resp
query := r.URL.Query()
phone := query["phone"][0]
// 1.手机号校验
// 2.获取随机验证码
code := randCode()
// 3. redis记录
redis.SetMini(phone, code,5)
// 4. 异步发送验证码
go func() {
// time.Sleep(time.Duration(10)*time.Second)
send(phone, code)
}()
// 5.返回
result.Msg = "success"
result.Data = code
if err := json.NewEncoder(w).Encode(result); err != nil {
log.Fatal(err)
}
}
6. 随机生成6位数短息验证码
// 6位随机验证码
func randCode() string {
rnd := rand.New(rand.NewSource(time.Now().UnixNano()))
rndCode := fmt.Sprintf("%06v", rnd.Int31n(1000000))
fmt.Println(rndCode)
return rndCode
}
7. redis的连接
package redis
import (
"log"
"strconv"
"github.com/go-redis/redis"
"fmt"
)
var server = "127.0.0.1"
var port = 6379
var password = ""
var db = 0
// 注意int转字符串
var addr = server + ":" + strconv.Itoa(port)
/*
基于go-redis
github地址:https://github.com/go-redis/redis
redis连接demo,连接数等自行设置
*/
func GetClient() (clint *redis.Client) {
fmt.Println(addr)
fmt.Println(port)
client := redis.NewClient(&redis.Options{
Addr: addr,
Password: password, // no password set
DB: db, // use default DB
})
pong, err := client.Ping().Result()
log.Println(pong, err)
return client
}
8. redis的工具类型如get或set
package redis
import (
"github.com/go-redis/redis"
_ "github.com/go-redis/redis"
"time"
)
/*
基于go-redis
github地址:https://github.com/go-redis/redis
设置小时demo
*/
func SetHour() (result *redis.StatusCmd) {
client := GetClient()
// 注意time.Hour 要乘以一个具体的数值
set := client.Set("hour", "3个小时", time.Hour*3)
return set
}
/*
基于go-redis
github地址:https://github.com/go-redis/redis
设置分钟demo
*/
func SetMini(key string, value string, i int64) (result *redis.StatusCmd) {
client := GetClient()
// 注意time.Minute 要乘以一个具体的数值
set := client.Set(key, value, time.Duration(i) * time.Minute)
return set
}
/*
基于go-redis
github地址:https://github.com/go-redis/redis
get的demo
*/
func Get(key string) string {
c := GetClient()
get := c.Get(key)
result, _ := get.Result()
return result
}
9. 基本的代码如上,如有疑问或需要源码欢迎留言沟通。