This commit is contained in:
2024-08-26 17:20:13 +08:00
commit 51090658a2
39 changed files with 2231 additions and 0 deletions

47
utils/exception/code.go Normal file
View File

@@ -0,0 +1,47 @@
package exception
const (
SUCCESS = 0 // 操作成功
ERROR = 10000 // 默认错误返回
SERVER_ERROR = 10001 // 服务器错误
UNKNOW_ERROR = 10002 // 未知错误
REMOTE_ERROR = 10003 // 远程服务错误
IP_LINMIT = 10004 // 地址限制
IP_LINMIT_CODE = 10014 // 地址限制需要验证码
NO_PERMISSION = 10005 // 未拥有授权
PARAMETER_ERROR = 10008 // 参数错误
RPC_ERROR = 10013 // RPC通讯错误
NOT_FOUND_ROUTE = 10020 // 未查询到路由
NOT_FOUND_METH = 10021 // 未查询到方式
NOT_FOUND = 10022 // 未查询到
AUTH_ERROR = 10023 // 认证错误
NO_VALID_TOKEN = 10024 // token无效
REPEAD = 10025 // 重复数据或操作
OUT_SLINCE = 10026 // 超出限制
DB_ERRROR = 10027 // 数据库错误
SENSITIVE = 10028 // 敏感词语
)
const (
//用户
NOT_FOUND_USER = 20001 // 未查询到用户
EXIST_USER = 20002 // 用户已存在
NO_BELONG_ACTION = 20003 // 越权操作
NO_PHONE = 20004 // 未验证手机号
//订单
ORDER_ERROR = 20100 // 订单统用错误
NO_ORDER = 20101 // 订单不存在
NO_PAID_ORDER = 20102 // 订单未支付
PAID_ORDER = 20103 // 订单已支付
EXPIRE_ORDER = 20104 // 订单超时
DONE_ORDER = 20105 // 订单已完结
NO_BELONG_ORDER = 20106 // 不属于自己的订单
//积分
SIGNED = 20200 // 已签到
NO_ENOUGH_POINT = 20201 // 积分不足
NO_ILLEGAL_CHANNEL = 20202 // 渠道非法
NO_ILLEGAL_SIGN = 20203 // 渠道非签到
)

View File

@@ -0,0 +1,81 @@
package exception
import (
"energy-management-system/utils"
"net/http"
"github.com/gin-gonic/gin"
)
type Exception struct {
HttpCode int `json:"-"`
Code int `json:"code"`
Msg interface{} `json:"msg"`
Err error `json:"err"`
}
type ExceptionResponse struct {
Code int `json:"code"`
Msg interface{} `json:"msg"`
Path string `json:"path"`
}
func (r *Exception) Error() interface{} {
return r.Msg
}
func NotFoundR(c *gin.Context) {
c.JSON(http.StatusForbidden, ExceptionResponse{NOT_FOUND_ROUTE, "Not Found Route", utils.GetReqPath(c)})
}
func NotFoundM(c *gin.Context) {
c.JSON(http.StatusForbidden, ExceptionResponse{NOT_FOUND_METH, "Not Found Method", utils.GetReqPath(c)})
}
func Panic(c *gin.Context, e *Exception) {
c.JSON(e.HttpCode, ExceptionResponse{e.Code, e.Msg, utils.GetReqPath(c)})
}
func Unknow(c *gin.Context) {
c.JSON(http.StatusForbidden, ExceptionResponse{UNKNOW_ERROR, "未知错误", utils.GetReqPath(c)})
}
func Server(c *gin.Context) {
c.JSON(http.StatusInternalServerError, ExceptionResponse{SERVER_ERROR, "服务器错误", utils.GetReqPath(c)})
}
// FailMsg 主动抛出错误Exception类型
func FailMsg(msg interface{}) *Exception {
return &Exception{http.StatusOK, ERROR, msg, nil}
}
func FailCodeMsg(code int, msg string) *Exception {
return &Exception{http.StatusOK, code, msg, nil}
}
func PanicMsg(msg interface{}) {
PanicMsgBool(true, msg)
}
func PanicCodeMsg(code int, msg string) {
PanicCodeMsgBool(true, code, msg)
}
func PanicMsgBool(flag bool, msg interface{}) {
if flag {
panic(&Exception{http.StatusOK, ERROR, msg, nil})
}
}
func PanicCodeMsgBool(flag bool, code int, msg string) {
if flag {
panic(&Exception{http.StatusOK, code, msg, nil})
}
}
func PanicMsgErr(err error, msg interface{}) {
if err != nil {
panic(&Exception{http.StatusOK, ERROR, msg, err})
}
}
func PanicCodeMsgErr(err error, code int, msg string) {
if err != nil {
panic(&Exception{http.StatusOK, code, msg, err})
}
}

189
utils/utils.go Normal file
View File

@@ -0,0 +1,189 @@
package utils
import (
"bytes"
"fmt"
"github.com/gin-gonic/gin"
"math"
"os"
"runtime"
"sort"
"strconv"
"strings"
"time"
)
func GetReqPath(c *gin.Context) string {
return c.Request.Method + " " + c.Request.URL.String()
}
func TimeFormat(t time.Time) string {
timeString := t.Format("2006/01/02 - 15:04:05")
return timeString
}
// GetMinutesFromTimeRange 接受时间范围字符串,返回开始分钟、结束分钟和总分钟数
func GetMinutesFromTimeRange(startTimeStr, endTimeStr string) (int, int, int, error) {
startTimeParts := strings.Split(startTimeStr, ":")
endTimeParts := strings.Split(endTimeStr, ":")
if len(startTimeParts) != 2 || len(endTimeParts) != 2 {
return 0, 0, 0, fmt.Errorf("时间格式不正确,应该是 HH:MM")
}
startHour, err := strconv.Atoi(startTimeParts[0])
if err != nil {
return 0, 0, 0, fmt.Errorf("无效的开始小时: %s", startTimeParts[0])
}
startMinute, err := strconv.Atoi(startTimeParts[1])
if err != nil {
return 0, 0, 0, fmt.Errorf("无效的开始分钟: %s", startTimeParts[1])
}
endHour, err := strconv.Atoi(endTimeParts[0])
if err != nil {
return 0, 0, 0, fmt.Errorf("无效的结束小时: %s", endTimeParts[0])
}
endMinute, err := strconv.Atoi(endTimeParts[1])
if err != nil {
return 0, 0, 0, fmt.Errorf("无效的结束分钟: %s", endTimeParts[1])
}
// 计算开始和结束的总分钟
startMinutes := startHour*60 + startMinute
endMinutes := endHour*60 + endMinute
// 判断开始时间和结束时间的大小关系
if startMinutes >= endMinutes {
return 0, 0, 0, fmt.Errorf("开始时间必须小于结束时间")
}
// 计算总分钟数
totalMinutes := endMinutes - startMinutes
return startMinutes, endMinutes, totalMinutes, nil
}
var (
dunno = []byte("???")
centerDot = []byte("·")
dot = []byte(".")
slash = []byte("/")
)
func Stack(skip int) {
var lines [][]byte
var lastFile string
for i := skip; ; i++ { // Skip the expected number of frames
pc, file, line, ok := runtime.Caller(i)
if !ok {
break
}
fmt.Printf("%s:%d (0x%x)\n", file, line, pc)
if file != lastFile {
data, err := os.ReadFile(file)
if err != nil {
continue
}
lines = bytes.Split(data, []byte{'\n'})
lastFile = file
}
fmt.Printf("\t%s: %s\n", function(pc), source(lines, line))
}
}
func source(lines [][]byte, n int) []byte {
n-- // in stack trace, lines are 1-indexed but our array is 0-indexed
if n < 0 || n >= len(lines) {
return dunno
}
return bytes.TrimSpace(lines[n])
}
// function returns, if possible, the name of the function containing the PC.
func function(pc uintptr) []byte {
fn := runtime.FuncForPC(pc)
if fn == nil {
return dunno
}
name := []byte(fn.Name())
// The name includes the path name to the package, which is unnecessary
// since the file name is already included. Plus, it has center dots.
// That is, we see
// runtime/debug.*T·ptrmethod
// and want
// *T.ptrmethod
// Also the package path might contains dot (e.g. code.google.com/...),
// so first eliminate the path prefix
if lastSlash := bytes.LastIndex(name, slash); lastSlash >= 0 {
name = name[lastSlash+1:]
}
if period := bytes.Index(name, dot); period >= 0 {
name = name[period+1:]
}
name = bytes.Replace(name, centerDot, dot, -1)
return name
}
// ExtractNumber 提取数字并返回整数
func ExtractNumber(id string) (int, error) {
parts := strings.Split(id, "_")
if len(parts) == 0 {
return 0, fmt.Errorf("无效的 Id: %s", id)
}
numStr := parts[0]
num, err := strconv.Atoi(numStr)
if err != nil {
return 0, fmt.Errorf("转换错误: %v", err)
}
return num, nil
}
// GetSplitIntMaxMin 函数返回切片中的最大值和最小值
func GetSplitIntMaxMin(nums []int) (max int, min int, err error) {
if len(nums) == 0 {
return 0, 0, fmt.Errorf("切片为空")
}
// 初始化最大值和最小值
max = math.MinInt64 // 设置为最小整数
min = math.MaxInt64 // 设置为最大整数
// 遍历切片,找到最大值和最小值
for _, num := range nums {
if num > max {
max = num
}
if num < min {
min = num
}
}
return max, min, nil
}
// SplitIntoGroups 切片根据是否连续来进行分组
func SplitIntoGroups(nums []int) [][]int {
if len(nums) == 0 {
return nil
}
// 将切片排序
sort.Ints(nums)
var groups [][]int
var currentGroup []int
// 初始化第一组
currentGroup = append(currentGroup, nums[0])
for i := 1; i < len(nums); i++ {
// 检查当前数字与前一个数字的差值
if nums[i] == nums[i-1]+1 {
// 如果是连续的,添加到当前组
currentGroup = append(currentGroup, nums[i])
} else {
// 如果不连续,保存当前组并开始新的一组
groups = append(groups, currentGroup)
currentGroup = []int{nums[i]} // 开始新的一组
}
}
// 添加最后一组
groups = append(groups, currentGroup)
return groups
}