改造登录功能
文档对应视频课程中4.3、4.4章节,请小伙伴们对应学习。
这里主要对代码做了一些注释,和视频配合学习效果更佳。
分析PHP代码
/**
* 通过手机号和密码登录
* @param string $mobile
* @param string $password
* @return \think\response\Json
*/
public function loginDo()
{
try{
//获取手机号
//获取密码
$mobile = Request::post('mobile', '');
$password = Request::post('password', '');
if(!$mobile){
throw new \Exception("手机号不能为空");
}
if(!$password){
throw new \Exception("密码不能为空");
}
if(!isMobile($mobile)){
throw new \Exception("手机号格式不正确");
}
//数据库中查找手机号和密码是否正确
$rs = User::isMobileLogin($mobile, Md5V($password));
if($rs){
returnSuccess([
'uid' => $rs['id'],
'name' => $rs['name']
]);
}
throw new \Exception("手机号或密码不正确");
} catch (\Exception $e) {
returnError(5000, $e->getMessage());
}
}
/**
* 根据手机号和密码获取数据
* @param string $mobile
* @param string $password
* @return rs
*/
public static function isMobileLogin($mobile, $password){
//根据表中mobile和password查询数据
$rs = Db::table('user')->where([
['mobile', '=', $mobile],
['password', '=', $password],
])
->select();
//有数据返回信息,无数据返回false
if(!$rs->isEmpty()){
return $rs[0];
}
return false;
}
上面是PHP端源码,分析接受参数和返回参数
接口地址:
/login/do
- 接收参数为:mobile(手机号),password(密码)
- 返回信息:json格式,items中返回uid和username
- 业务逻辑:
Go中实现功能
//用户登录
// @router /login/do [*]
func (this *UserController) LoginDo() {
mobile := this.GetString("mobile")
password := this.GetString("password")
if mobile == "" {
this.Data["json"] = ReturnError(4001, "手机号不能为空")
this.ServeJSON()
}
isorno, _ := regexp.MatchString(`^1(3|4|5|7|8)[0-9]\d{8}$`, mobile)
if !isorno {
this.Data["json"] = ReturnError(4002, "手机号格式不正确")
this.ServeJSON()
}
if password == "" {
this.Data["json"] = ReturnError(4003, "密码不能为空")
this.ServeJSON()
}
uid, name := models.IsMobileLogin(mobile, MD5V(password))
if uid != 0 {
//同样返回uid和username
this.Data["json"] = ReturnSuccess(0, "登录成功", map[string]interface{}{"uid": uid, "username": name}, 1)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(4004, "手机号或密码不正确")
this.ServeJSON()
}
}