封装responseEx

master
ZGGSONG 3 years ago
parent c61aebab73
commit 5b7d572f83

@ -18,11 +18,11 @@ func Login(ctx *gin.Context) {
// 数据验证 // 数据验证
if len(telephone) != 11 { if len(telephone) != 11 {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "手机号必须是11位") response.Fail(ctx, nil, "手机号必须是11位")
return return
} }
if len(password) < 6 { if len(password) < 6 {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码必须大于6位") response.Fail(ctx, nil, "密码必须大于6位")
return return
} }
@ -30,13 +30,13 @@ func Login(ctx *gin.Context) {
var user model.User var user model.User
DB.Where("telephone = ?", telephone).First(&user) DB.Where("telephone = ?", telephone).First(&user)
if user.ID == 0 { if user.ID == 0 {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "用户不存在") response.Fail(ctx, nil, "用户不存在")
return return
} }
// 密码验证 // 密码验证
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil { if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码错误") response.Fail(ctx, nil, "密码错误")
return return
} }

@ -21,11 +21,11 @@ func Register(ctx *gin.Context) {
// 数据验证 // 数据验证
if len(telephone) != 11 { if len(telephone) != 11 {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "手机号必须是11位") response.Fail(ctx, nil, "手机号必须是11位")
return return
} }
if len(password) < 6 { if len(password) < 6 {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "密码必须大于6位") response.Fail(ctx, nil, "密码必须大于6位")
return return
} }
// 如果名字为空则返回10为随机字符串 // 如果名字为空则返回10为随机字符串
@ -35,7 +35,7 @@ func Register(ctx *gin.Context) {
// 判断手机号是否存在 // 判断手机号是否存在
if isExistTelephone(DB, telephone) { if isExistTelephone(DB, telephone) {
response.Response(ctx, http.StatusUnprocessableEntity, 400, nil, "用户已存在") response.Fail(ctx, nil, "用户已存在")
return return
} }

@ -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)
}
Loading…
Cancel
Save