改造注册功能
文档对应视频课程中4.3、4.4章节,请小伙伴们对应学习。
这里主要对代码做了一些注释,和视频配合学习效果更佳。
分析PHP代码
/**
* 注册用户
* @param string $mobile
* @param string $password
* @return \think\response\Json
*/
public function saveRegister(){
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::isUserMobile($mobile);
if($rs){
throw new \Exception("手机号已经注册");
} else {
//保存用户信息,密码有MD5加密
$rs = User::userSave($mobile, Md5V($password));
if($rs){
//返回成功状态
returnSuccess('注册成功');
}
}
throw new \Exception("注册失败,请联系客服");
} catch (\Exception $e) {
returnError(5000, $e->getMessage());
}
}
//单独封装的返回正确状态的函数,统一调用
function returnSuccess($data, $count = 0){
$return = [
'code' => 0,
'items' => $data,
'count' => $count
];
echo json_encode($return);
exit;
}
上面是PHP端源码,分析接受参数和返回参数
接口地址:
/register/save
- 接收参数为:mobile(手机号),password(密码)
- 返回信息:json格式,其中 code(状态码,0=正确),items(返回信息),count(条数)
- 业务逻辑:
Go中实现功能
//用户注册功能
// @router /register/save [post]
func (this *UserController) SaveRegister() {
var (
mobile string
password string
err error
)
//接受手机号和密码
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()
}
//判断手机号是否已经注册
status := models.IsUserMobile(mobile)
if status {
this.Data["json"] = ReturnError(4005, "此手机号已经注册")
this.ServeJSON()
} else {
//保存用户信息,密码MD5加密
err = models.UserSave(mobile, MD5V(password))
if err == nil {
this.Data["json"] = ReturnSuccess(0, "注册成功", nil, 0)
this.ServeJSON()
} else {
this.Data["json"] = ReturnError(5000, err)
this.ServeJSON()
}
}
}
type JsonStruct struct {
Code int `json:"code"`
Msg interface{} `json:"msg"`
Items interface{} `json:"items"`
Count int64 `json:"count"`
}
//封装返回函数,保存和PHP端一致
func ReturnSuccess(code int, msg interface{}, items interface{}, count int64) (json *JsonStruct) {
json = &JsonStruct{Code: code, Msg: msg, Items: items, Count: count}
return
}