概要
实现用户注册功能
新建error.go文件
$ touch ~/book/user/api/internal/logic/error.go
填充如下代码
package logic import ( "book/shared" ) var ( errorDuplicateUsername = shared.NewDefaultError("用户名已经注册") errorDuplicateMobile = shared.NewDefaultError("手机号已经被占用") )
填充注册逻辑代码
$ vi ~/book/user/api/internal/logic/registerlogic.go
增加注册逻辑
向Register方法中填充注册逻辑
// 为了简单,这里只做一下简单的逻辑校验 _, err := l.svcCtx.UserModel.FindOneByName(req.Username) if err == nil { return errorDuplicateUsername } _, err = l.svcCtx.UserModel.FindOneByMobile(req.Mobile) if err == nil { return errorDuplicateMobile } _, err = l.svcCtx.UserModel.Insert(model.User{ Name: req.Username, Password: req.Password, Mobile: req.Mobile, Gender: "男", Nickname: "admin", }) return err
访问注册协议
$ curl -i -X POST \ http://127.0.0.1:8888/user/register \ -H 'cache-control: no-cache' \ -H 'content-type: application/json' \ -d '{ "username":"admin", "password":"666666", "mobile":"19988888888" }'
得到响应码为200
则代表注册成功
shared中文件代码
新建baseerror.go
$ touch ~/book/shared/baseerror.go
填充如下代码
package shared const ( defaultCode = 1001 ) type ( CodeError struct { Code int `json:"code"` Msg string `json:"msg"` } ) func NewCodeError(code int, msg string) error { return &CodeError{Code: code, Msg: msg} } func NewDefaultError(msg string) error { return NewCodeError(defaultCode, msg) } func (e *CodeError) Error() string { return e.Msg }