错误码标准化,接口返回错误代码,以供前端使用查看。
创建 /utils/errmsg/errmsg.go
package errmsg
const (
SUCCSE = 200
ERROR = 500
// code= 1000... 用户模块的错误
ERROR_USERNAME_USED = 1001
ERROR_PASSWORD_WRONG = 1002
//...
)
var codemsg = map[int]string{
SUCCSE: "ok",
ERROR: "FAIL",
ERROR_USERNAME_USED: "用户名已存在!",
ERROR_PASSWORD_WRONG: "密码错误",
//...
}
func GetErrMsg(code int) string {
return codemsg[code]
}
model/Article.go
api/v1/article.go
以查询用户列表为例
api/v1/user.go
//查询用户列表
func GetUsers(c *gin.Context) {
pageSize, _ := strconv.Atoi(c.Query("pagesize"))
pageNum, _ := strconv.Atoi(c.Query("pagenum"))
username := c.Query("username")
switch {
case pageSize >= 100:
pageSize = 100
case pageSize <= 0:
pageSize = 10
}
if pageNum == 0 {
pageNum = 1
}
data, total := model.GetUsers(username, pageSize, pageNum)
code := errmsg.SUCCSE
c.JSON(
http.StatusOK, gin.H{
"status": code,
"data": data,
"total": total,
"message": errmsg.GetErrMsg(code),
},
)
}
model/User.go
//GetUsers 查询用户列表
func GetUsers(username string, pageSize, pageNum int) ([]User, int64) {
var users []User
var total int64
if username != "" {
db.Select("id,username,role,created_at").Where(
"username LIKE ?", username+"%",
).Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users)
db.Model(&users).Where(
"username LIKE ?", username+"%",
).Count(&total)
return users, total
}
db.Select("id,username,role,created_at").Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users)
db.Model(&users).Count(&total)
return users, total
}
例如 model/Uesr.go 中:
type User struct {
gorm.Model
Username string `gorm:"type:varchar(20);not null " json:"username" validate:"required,min=4,max=12" label:"用户名"`
Password string `gorm:"type:varchar(500);not null" json:"password" validate:"required,min=6,max=120" label:"密码"`
Role int `gorm:"type:int;DEFAULT:2" json:"role" validate:"required,gte=2" label:"角色码"`
}
package validator
import (
"fmt"
"ginVue3blog/utils/errmsg"
//注意需要引入如下4个包
"github.com/go-playground/locales/zh_Hans_CN" //中文包
unTrans "github.com/go-playground/universal-translator" //翻译包
"github.com/go-playground/validator/v10"
zhTrans "github.com/go-playground/validator/v10/translations/zh"
"reflect"
)
func Validate(data interface{}) (string, int) {
validate := validator.New()
uni := unTrans.New(zh_Hans_CN.New())
trans, _ := uni.GetTranslator("zh_Hans_CN")
err := zhTrans.RegisterDefaultTranslations(validate, trans)
if err != nil {
fmt.Println("err:", err)
}
validate.RegisterTagNameFunc(func(field reflect.StructField) string {
label := field.Tag.Get("label")
return label
})
err = validate.Struct(data)
if err != nil {
for _, v := range err.(validator.ValidationErrors) {
return v.Translate(trans), errmsg.ERROR
}
}
return "", errmsg.ERROR
}
图片及部分相关技术知识点来源于网络搜索,侵权删!