diff --git a/controller/login.go b/controller/login.go index 9104ce8..8c602c2 100644 --- a/controller/login.go +++ b/controller/login.go @@ -18,11 +18,11 @@ func Login(ctx *gin.Context) { // 数据验证 if len(telephone) != 11 { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "手机号必须是11位") + response.Fail(ctx, nil, "手机号必须是11位") return } if len(password) < 6 { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码必须大于6位") + response.Fail(ctx, nil, "密码必须大于6位") return } @@ -30,13 +30,13 @@ func Login(ctx *gin.Context) { var user model.User DB.Where("telephone = ?", telephone).First(&user) if user.ID == 0 { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "用户不存在") + response.Fail(ctx, nil, "用户不存在") return } // 密码验证 if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码错误") + response.Fail(ctx, nil, "密码错误") return } diff --git a/controller/register.go b/controller/register.go index 6bc169f..e5c32dc 100644 --- a/controller/register.go +++ b/controller/register.go @@ -21,11 +21,11 @@ func Register(ctx *gin.Context) { // 数据验证 if len(telephone) != 11 { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "手机号必须是11位") + response.Fail(ctx, nil, "手机号必须是11位") return } if len(password) < 6 { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码必须大于6位") + response.Fail(ctx, nil, "密码必须大于6位") return } // 如果名字为空则返回10为随机字符串 @@ -35,7 +35,7 @@ func Register(ctx *gin.Context) { // 判断手机号是否存在 if isExistTelephone(DB, telephone) { - response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "用户已存在") + response.Fail(ctx, nil, "用户已存在") return } diff --git a/response/response.go b/response/response.go new file mode 100644 index 0000000..7dd1ab1 --- /dev/null +++ b/response/response.go @@ -0,0 +1,23 @@ +package response + +import ( + "net/http" + + "github.com/gin-gonic/gin" +) + +func Response(ctx *gin.Context, httpStatus int, code int, data gin.H, msg string) { + ctx.JSON(httpStatus, gin.H{ + "code": code, + "data": data, + "msg": msg, + }) +} + +func Success(ctx *gin.Context, data gin.H, msg string) { + Response(ctx, http.StatusOK, 200, data, msg) +} + +func Fail(ctx *gin.Context, data gin.H, msg string) { + Response(ctx, http.StatusOK, 400, data, msg) +}