# 用户注册

# 概要


实现用户注册功能


# 新建error.go文件


```bash
$  touch book/user/api/internal/logic/error.go
```


填充如下代码


```bash
package logic

import "book/shared"

var (
	errorDuplicateUsername = shared.NewDefaultError("用户名已经注册")
	errorDuplicateMobile   = shared.NewDefaultError("手机号已经被占用")
)
```


> NOTE: shared代码见文章尾部[shared中文件代码](#shared中文件代码)



# 填充注册逻辑代码


```bash
$ vi book/user/api/internal/logic/registerlogic.go
```


增加注册逻辑


向Register方法中填充注册逻辑


```go
// 为了简单，这里只做一下简单的逻辑校验
_, 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
```


# 访问注册协议


```bash
$ 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"
}'
```
> 注意：windows系统curl json需要对json进行转义。

得到响应码为`200`则代表注册成功


![curl-register.png](https://cdn.nlark.com/yuque/0/2020/png/465993/1603460056211-23748648-65c1-4472-97ae-3dfa255aecd1.png#align=left&display=inline&height=580&margin=%5Bobject%20Object%5D&name=curl-register.png&originHeight=580&originWidth=2224&size=108027&status=done&style=none&width=2224)


# shared中文件代码


新建baseerror.go


```bash
$ touch book/shared/baseerror.go
```


填充如下代码


```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
}
```

<Vssue title="用户注册" />

