feat:调整结构

This commit is contained in:
wolter 2024-11-27 17:20:42 +08:00
parent 16eddb135c
commit afcd977b0c
19 changed files with 269 additions and 227 deletions

View File

@ -0,0 +1,13 @@
package errorcode
var (
Success = &BusinessErr{code: 200, message: "成功"}
ParamError = &BusinessErr{code: 400, message: "参数错误"}
NotAuth = &BusinessErr{code: 401, message: "未经授权"}
NotLogin = &BusinessErr{code: 401, message: "未经授权"}
Forbidden = &BusinessErr{code: 403, message: "请求被禁止"}
NotFound = &BusinessErr{code: 404, message: "未找到"}
SystemError = &BusinessErr{code: 500, message: "系统错误"}
)

View File

@ -0,0 +1,27 @@
package errorcode
type BusinessErr struct {
code int32
message string
}
func (e *BusinessErr) Error() string {
return e.message
}
func (e *BusinessErr) Code() int32 {
return e.code
}
func (e *BusinessErr) Is(target error) bool {
_, ok := target.(*BusinessErr)
return ok
}
// CustomErr 自定义错误
func NewBusinessErr(code int32, message string) *BusinessErr {
return &BusinessErr{code: code, message: message}
}
func (e *BusinessErr) Wrap(err error) *BusinessErr {
return NewBusinessErr(e.code, err.Error())
}

View File

@ -1,52 +0,0 @@
package errorcode
const (
//成功
Success = 200
//参数错误
ParamError = 400
//未经授权
NotAuth = 401
//请求被禁止
Forbidden = 403
//找不到页面
NotFound = 404
//系统错误
SystemError = 500
//未登录
NotLogin = 1000
)
var MsgEN = map[int]string{
Success: "success",
ParamError: "param error",
NotAuth: "not authorized",
Forbidden: "forbidden",
NotFound: "not found",
SystemError: "system error",
}
var MsgZH = map[int]string{
Success: "请求成功",
ParamError: "参数错误",
NotFound: "数据不存在",
NotAuth: "未经授权",
NotLogin: "未登录",
}
var MsgMap map[string]map[int]string = map[string]map[int]string{"en": MsgZH}
func GetMsg(code int, local string) string {
if local == "" {
local = "en"
}
if msg, ok := MsgMap[local][code]; ok {
return msg
}
return ""
}

View File

@ -0,0 +1,40 @@
package backend
import (
"cron_admin/app/http/controllers"
"cron_admin/app/http/entities"
"cron_admin/app/http/entities/backend"
"cron_admin/app/models/cronreportchannelmodel"
"cron_admin/app/services"
"github.com/ahmetb/go-linq/v3"
"github.com/gin-gonic/gin"
)
func ReportChannelCreate(c *gin.Context) {
req, _ := controllers.GetRequest(c).(*backend.ReportChannelCreateRequest)
reportChannel := req.Request2DB()
err := services.ReportChannelCreate(&reportChannel)
controllers.HandRes(c, req, err)
}
func ReportChannelList(c *gin.Context) {
req, _ := controllers.GetRequest(c).(*backend.ReportChannelListRequest)
data, total, err := services.ReportChannelList(*req)
if err != nil {
controllers.HandRes(c, nil, err)
return
}
list := make([]backend.ReportChannelListResponse, 0, len(data))
linq.From(data).SelectT(func(in cronreportchannelmodel.CronReportChannel) backend.ReportChannelListResponse {
var out backend.ReportChannelListResponse
out.FromDb(in)
return out
}).ToSlice(&list)
controllers.HandRes(c, entities.PageRsp{
Total: total,
Data: list,
}, nil)
}

View File

@ -14,7 +14,7 @@ func DbList(c *gin.Context) {
request := controllers.GetRequest(c).(*backend.DbListRequest)
count, DbListInfo, err := db_service.DbList(request, request.Page, request.Limit)
if err != nil {
controllers.HandCodeRes(c, nil, errorcode.ParamError)
controllers.HandRes(c, nil, errorcode.ParamError)
} else {
var DbListResponse []backend.DbListResponse
_ = mapstructure.DecodeWithTime(DbListInfo, &DbListResponse, helper.DefaultFormatLayout)

View File

@ -18,7 +18,7 @@ func List(c *gin.Context) {
request := controllers.GetRequest(c).(*backend.UserListRequest)
count, list, err := services.GetListByWhere(request, request.Page, request.PageSize)
if err != nil {
controllers.HandCodeRes(c, nil, errorcode.NotFound)
controllers.HandRes(c, nil, errorcode.NotFound)
} else {
UserList := make([]backend.UserListResponse, 0)
linq.From(list).SelectT(func(in userinfomodel.UserInfo) (d backend.UserListResponse) {
@ -33,7 +33,7 @@ func GerUserInfoHandler(c *gin.Context) {
request := controllers.GetRequest(c).(*backend.UserInfoRequest)
has, userInfo, err := services.UserInfo(request.Id)
if err != nil || has == false {
controllers.HandCodeRes(c, nil, errorcode.NotFound)
controllers.HandRes(c, nil, errorcode.NotFound)
} else {
UserInfoResponse := backend.UserListResponse{}
UserInfoResponse.ResponseFromDb(userInfo)

View File

@ -2,7 +2,7 @@ package controllers
import (
"bytes"
"context"
"cron_admin/app/constants/errorcode"
"cron_admin/app/utils"
"cron_admin/config"
"encoding/base64"
@ -10,40 +10,15 @@ import (
"errors"
"github.com/go-playground/locales/zh"
ut "github.com/go-playground/universal-translator"
"github.com/qit-team/snow-core/redis"
"github.com/qit-team/snow-core/log/logger"
"gopkg.in/go-playground/validator.v9"
zh_translations "gopkg.in/go-playground/validator.v9/translations/zh"
"io/ioutil"
"net/http"
"cron_admin/app/constants/errorcode"
"github.com/gin-gonic/gin"
)
/**
* 成功时返回
*/
func Success(c *gin.Context, data interface{}, message string) {
if message == "" {
message = errorcode.GetMsg(errorcode.Success, c.GetHeader("local"))
}
if config.GetConf().Env == "production" {
c.String(http.StatusOK, EncriptJson(gin.H{
"code": errorcode.Success,
"message": message,
"data": data,
}))
} else {
c.JSON(http.StatusOK, gin.H{
"code": errorcode.Success,
"message": message,
"data": data,
})
}
c.Abort()
}
func EncriptJson(h gin.H) string {
var data, err = json.Marshal(h)
if err != nil {
@ -54,44 +29,12 @@ func EncriptJson(h gin.H) string {
return res
}
/**
* 失败时返回
*/
func Error(c *gin.Context, code int, msg ...string) {
message := ""
if len(msg) > 0 {
message = msg[0]
} else {
message = errorcode.GetMsg(code, "")
}
if config.GetConf().Env == "production" {
c.String(http.StatusOK, EncriptJson(gin.H{
"code": code,
"message": message,
"data": make(map[string]string),
}))
} else {
c.JSON(http.StatusOK, gin.H{
"code": code,
"message": message,
"data": make(map[string]string),
})
}
c.Abort()
}
func Error404(c *gin.Context) {
Error(c, errorcode.NotFound, "路由不存在")
HandRes(c, nil, errorcode.NotFound)
}
func Error500(c *gin.Context) {
Error(c, errorcode.SystemError)
}
type HTTPError struct {
Code int `json:"code" example:"400"`
Message string `json:"message" example:"status bad request"`
HandRes(c, nil, errorcode.SystemError)
}
/**
@ -120,7 +63,7 @@ func GenRequest(c *gin.Context, request interface{}) (msgs []string, err error)
for _, v := range errValidate.(validator.ValidationErrors) {
msgs = append(msgs, v.Translate(trans))
}
err = errors.New(errorcode.GetMsg(errorcode.ParamError, ""))
err = errorcode.ParamError
return
}
}
@ -143,22 +86,36 @@ func GetRequest(c *gin.Context) interface{} {
}
func HandRes(c *gin.Context, data interface{}, err error) {
var bizErr *errorcode.BusinessErr
if err == nil {
Success(c, data, "请求成功")
bizErr = errorcode.Success
} else {
Error(c, errorcode.SystemError, err.Error())
if errors.Is(err, &errorcode.BusinessErr{}) {
errors.As(err, &bizErr)
} else {
utils.Log(c, "系统错误", err.Error())
logger.GetLogger().Error()
bizErr = errorcode.SystemError
}
}
}
func HandCodeRes(c *gin.Context, data interface{}, code int) {
if utils.IsNil(data) {
data = struct{}{}
if data == nil {
data = gin.H{}
}
if code == errorcode.Success {
Success(c, data, errorcode.GetMsg(code, c.GetHeader("local")))
jsonData := gin.H{
"code": bizErr.Code(),
"message": bizErr.Error(),
"data": data,
}
if config.GetConf().Env == "production" {
c.String(http.StatusOK, EncriptJson(jsonData))
} else {
Error(c, code, errorcode.GetMsg(code, c.GetHeader("local")))
c.JSON(http.StatusOK, jsonData)
}
c.Abort()
}
func GetPlayerId(c *gin.Context) string {
playerId, _ := c.Get("playerId")
if playerId == nil {
@ -166,12 +123,3 @@ func GetPlayerId(c *gin.Context) string {
}
return playerId.(string)
}
func Frequence(key string) bool {
if rs := redis.GetRedis().Exists(context.Background(), utils.GetRealKey(key)); rs.String() != "" {
return false
} else {
redis.GetRedis().SetEX(context.Background(), utils.GetRealKey(key), 1, 5)
return true
}
}

View File

@ -1,12 +0,0 @@
package domains
type Filter struct {
Page int `json:"page"`
PageSize int `json:"page_size"`
}
type ProductFilter struct {
Page int `json:"page" form:"page"`
PageSize int `json:"page_size" form:"page_size"`
ProductName string `json:"product_name" form:"product_name"`
}

View File

@ -1,23 +0,0 @@
package domains
import "time"
type Product struct {
Id int
ProductName string
ProductType int
PacketRule int
ProductKind int
Amount string
CouponType int
IsSuperposition int
TemplateId int
Status int
IsNeedBill int
CreateTime time.Time
SupplierProductId int64
SupplierProductName string
Creator string
UpdateTime time.Time
}

View File

@ -0,0 +1,45 @@
package backend
import (
"cron_admin/app/http/entities"
"cron_admin/app/models/cronreportchannelmodel"
)
type ReportChannelListRequest struct {
entities.PageRequest
ReportChannelId int `json:"report_channel_id" validate:"min=0"`
Status int `json:"status"`
}
type ReportChannelListResponse struct {
ReportChannelId uint `json:"report_channel_id"`
ClientKey string `json:"client_key"`
ClientSecret string `json:"client_secret"`
Config string `json:"config"`
CreateTime string `json:"create_time"`
Status int `json:"status"`
}
func (this *ReportChannelListResponse) FromDb(in cronreportchannelmodel.CronReportChannel) {
this.ReportChannelId = in.ReportChannelId
this.ClientKey = in.ClientKey
this.ClientSecret = in.ClientSecret
this.Config = in.Config
this.CreateTime = in.CreateTime.Format("2006-01-02 15:04:05")
this.Status = in.Status
}
type ReportChannelCreateRequest struct {
ClientKey string `json:"client_key"`
ClientSecret string `json:"client_secret"`
Config string `json:"config"`
Status int `json:"status"`
}
func (this *ReportChannelCreateRequest) Request2DB() (db cronreportchannelmodel.CronReportChannel) {
db.ClientKey = this.ClientKey
db.ClientSecret = this.ClientSecret
db.Config = this.Config
db.Status = this.Status
return db
}

View File

@ -10,6 +10,6 @@ type PageRequest struct {
}
type PageRsp struct {
Total int64 `json:"total"`
Data []interface{} `json:"data"`
Total int64 `json:"total"`
Data interface{} `json:"data"`
}

View File

@ -1,15 +1,12 @@
package middlewares
import (
"context"
"cron_admin/app/constants/common"
"cron_admin/app/constants/errorcode"
"cron_admin/app/http/controllers"
"cron_admin/app/http/requestmapping"
"cron_admin/app/utils"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/qit-team/snow-core/redis"
"strings"
)
@ -18,14 +15,14 @@ func Auth() gin.HandlerFunc {
c.ClientIP()
var tokens = strings.SplitN(c.GetHeader("Authorization"), " ", 2)
if len(tokens) != 2 || tokens[0] != "Bearer" {
controllers.HandCodeRes(c, nil, errorcode.NotLogin)
controllers.HandRes(c, nil, errorcode.NotLogin)
c.Abort()
return
}
// 验证token
token, claims, err := utils.ParseToken(tokens[1])
if err != nil || !token.Valid {
controllers.HandCodeRes(c, nil, errorcode.NotAuth)
controllers.HandRes(c, nil, errorcode.NotAuth)
c.Abort()
return
}
@ -35,7 +32,7 @@ func Auth() gin.HandlerFunc {
c.Next()
return
} else {
controllers.HandCodeRes(c, nil, errorcode.NotAuth)
controllers.HandRes(c, nil, errorcode.NotAuth)
c.Abort()
}
}
@ -57,26 +54,6 @@ func Cors() gin.HandlerFunc {
}
}
func AdminAuth() gin.HandlerFunc {
return func(c *gin.Context) {
var token = c.GetHeader("token")
//将token放入redis
var playerId, err = redis.GetRedis().Get(context.Background(), utils.GetRealKey(common.TOKEN_Admin+token)).Result()
if rs, errRedis := redis.GetRedis().SIsMember(context.Background(), "disabled_uids", playerId).Result(); errRedis == nil && rs {
err = errors.New(errorcode.GetMsg(errorcode.NotFound, ""))
redis.GetRedis().SRem(context.Background(), "disabled_uids", playerId)
}
if err == nil {
c.Set("playerId", playerId)
c.Next()
return
} else {
controllers.HandCodeRes(c, nil, errorcode.Forbidden)
c.Abort()
}
}
}
func ValidateRequest() gin.HandlerFunc {
return func(c *gin.Context) {
var path = c.FullPath()
@ -88,13 +65,13 @@ func ValidateRequest() gin.HandlerFunc {
}
if handler == nil {
utils.Log(c, "path", path)
controllers.HandCodeRes(c, nil, errorcode.NotFound)
controllers.HandRes(c, nil, errorcode.NotFound)
} else {
v := handler()
msg, err := controllers.GenRequest(c, v)
if err != nil {
utils.Log(c, "path", path)
controllers.Error(c, errorcode.ParamError, msg...)
controllers.HandRes(c, nil, errorcode.ParamError.Wrap(fmt.Errorf("%s", strings.Join(msg, ","))))
} else {
c.Set("request", v)
c.Next()

View File

@ -52,7 +52,8 @@ func RegisterAdminRoute(router *gin.Engine) {
//消息管理
mes := v1.Group("/channel")
{
mes.GET("/list", backend.Empty)
mes.GET("/list", backend.ReportChannelList)
mes.POST("/create", backend.ReportChannelCreate)
}
//日志

View File

@ -1,4 +1,11 @@
package models
import (
"cron_admin/app/models/cronreportchannelmodel"
"cron_admin/app/models/userinfomodel"
)
type PO interface {
cronreportchannelmodel.CronReportChannel |
userinfomodel.UserInfo
}

View File

@ -0,0 +1,42 @@
package cronreportchannelmodel
import (
"github.com/qit-team/snow-core/db"
"sync"
"time"
)
var (
once sync.Once
m *CronReportChannelModel
)
// 实体
type CronReportChannel struct {
ReportChannelId uint `xorm:"'report_channel_id' UNSIGNED INT pk autoincr"`
ClientKey string `xorm:"'client_key' varchar(20)"`
ClientSecret string `xorm:"'client_secret' varchar(50)"`
Config string `xorm:"'config' JSON"`
CreateTime time.Time `xorm:"'create_time' created timestamp"`
UpdateTime time.Time `xorm:"'update_time' updated timestamp"`
Status int `xorm:"'status' TINYINT"`
}
// 表名
func (m *CronReportChannel) TableName() string {
return "cron_report_channel"
}
// 私有化防止被外部new
type CronReportChannelModel struct {
db.Model //组合基础Model集成基础Model的属性和方法
}
// 单例模式
func GetInstance() *CronReportChannelModel {
once.Do(func() {
m = new(CronReportChannelModel)
//m.DiName = "" //设置数据库实例连接默认db.SingletonMain
})
return m
}

View File

@ -4,6 +4,7 @@ import (
"cron_admin/app/http/entities"
"cron_admin/app/models"
"github.com/pkg/errors"
"github.com/qit-team/snow-core/db"
"time"
"xorm.io/xorm"
@ -14,6 +15,7 @@ type CommonRepo[P models.PO] struct {
}
type ICommonRepo[P models.PO] interface {
GetSession() *xorm.Session
FindAll(list *[]P, opts ...DBOption) error
FindAndCount(list *[]P, opts ...DBOption) (int64, error)
Get(db *P, opts ...DBOption) (bool, error)
@ -22,6 +24,7 @@ type ICommonRepo[P models.PO] interface {
InsertOne(db *P, opts ...DBOption) (int64, error)
InsertBatch(db *[]P, opts ...DBOption) (int64, error)
WithSession(session *xorm.Session) ICommonRepo[P]
WithByID(id uint) DBOption
WithByUserId(userId uint) DBOption
WithByBrandId(id int) DBOption
@ -36,8 +39,17 @@ type ICommonRepo[P models.PO] interface {
WithByProductId(productId uint) DBOption
}
func NewCommonRepo[P models.PO](repo *xorm.Session) ICommonRepo[P] {
return &CommonRepo[P]{repo: repo}
func NewCommonRepo[P models.PO]() ICommonRepo[P] {
return &CommonRepo[P]{}
}
func (this *CommonRepo[P]) WithSession(session *xorm.Session) ICommonRepo[P] {
this.repo = session
return this
}
func (this *CommonRepo[P]) GetSession() *xorm.Session {
return this.repo
}
func (this *CommonRepo[P]) FindAll(list *[]P, opts ...DBOption) error {
@ -77,6 +89,9 @@ func (this *CommonRepo[P]) InsertBatch(db *[]P, opts ...DBOption) (int64, error)
}
func getDb(repo *xorm.Session, opts ...DBOption) *xorm.Session {
if repo == nil {
repo = db.GetDb().NewSession()
}
for _, opt := range opts {
repo = opt(repo)
}

View File

@ -88,7 +88,7 @@ func (c *CommonRepo[P]) WithIdsNotIn(ids []uint) DBOption {
func (c *CommonRepo[P]) WithPage(pageFilter entities.PageRequest) DBOption {
return func(g *xorm.Session) *xorm.Session {
return g.Limit(pageFilter.PageSize, pageFilter.PageSize*(pageFilter.Page-1))
return g.Limit(pageFilter.Limit, pageFilter.Limit*(pageFilter.Page-1))
}
}
func (c *CommonRepo[P]) WithByCouponId(couponId uint) DBOption {

View File

@ -1,22 +0,0 @@
package repository
import (
"cron_admin/app/models"
"xorm.io/xorm"
)
type UserRepo[P models.PO] struct {
repo *xorm.Session
CommonRepo ICommonRepo[P]
}
func NewUserRepo[P models.PO](repo *xorm.Session) *UserRepo[P] {
commonRepo := NewCommonRepo[P](repo)
return &UserRepo[P]{repo: repo, CommonRepo: commonRepo}
}
func (c *UserRepo[P]) WithByCustNo(custNo string) DBOption {
return func(g *xorm.Session) *xorm.Session {
return g.Where("custNo = ?", custNo)
}
}

View File

@ -0,0 +1,36 @@
package services
import (
"cron_admin/app/http/entities/backend"
"cron_admin/app/models/cronreportchannelmodel"
"cron_admin/app/repository"
)
func ReportChannelCreate(param *cronreportchannelmodel.CronReportChannel) (err error) {
var (
repo = repository.NewCommonRepo[cronreportchannelmodel.CronReportChannel]()
)
_, err = repo.InsertOne(param)
return
}
func ReportChannelList(param backend.ReportChannelListRequest) (list []cronreportchannelmodel.CronReportChannel, total int64, err error) {
var (
repo = repository.NewCommonRepo[cronreportchannelmodel.CronReportChannel]()
opts = make([]repository.DBOption, 0)
)
if param.ReportChannelId > 0 {
opts = append(opts, repo.WithByID(uint(param.ReportChannelId)))
}
if param.Status > 0 {
opts = append(opts, repo.WithByStatus(param.Status))
}
if param.Page > 0 || param.Limit > 0 {
opts = append(opts, repo.WithPage(param.PageRequest))
}
total, err = repo.FindAndCount(&list, opts...)
return
}