import cycle not allowed

This commit is contained in:
2023-01-18 17:46:25 +08:00
parent 8d3a64b26e
commit 26f46f1eb6
35 changed files with 355 additions and 341 deletions
+7 -6
View File
@@ -1,8 +1,9 @@
package cache
import (
"cutego/pkg/common"
"cutego/pkg/constant"
"cutego/pkg/logging"
"cutego/pkg/util"
"cutego/refs"
)
@@ -18,7 +19,7 @@ func RemoveList(list []string) {
func RemoveCache(key string) int {
del, err := refs.RedisDB.DEL(key)
if err != nil {
common.ErrorLog(err)
logging.ErrorLog(err)
}
return del
}
@@ -29,7 +30,7 @@ func RemoveCache(key string) int {
func GetCache(key string) string {
val, err := refs.RedisDB.GET(key)
if err != nil {
common.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error())
logging.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error())
return ""
}
return val
@@ -40,9 +41,9 @@ func GetCache(key string) string {
// @Param value 值
// @Return 新增的行数
func SetCache(key string, value interface{}) int {
n, err := refs.RedisDB.SET(key, common.StructToJson(value))
n, err := refs.RedisDB.SET(key, util.StructToJson(value))
if err != nil {
common.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error())
logging.ErrorLog(constant.RedisConst{}.GetRedisError(), err.Error())
return 0
}
return int(n)
@@ -54,5 +55,5 @@ func SetCache(key string, value interface{}) int {
// @Param sec 过期时间(单位: 秒)
// @Return 新增的行数
func SetCacheTTL(key string, value interface{}, sec int) {
refs.RedisDB.SETEX(key, sec, common.StructToJson(value))
refs.RedisDB.SETEX(key, sec, util.StructToJson(value))
}
-166
View File
@@ -1,166 +0,0 @@
package common
import (
"cutego/pkg/config"
"encoding/json"
"fmt"
"os"
"runtime"
"strconv"
)
// IntToString int转string
func IntToString(n int) string {
return strconv.Itoa(n)
}
// StringToInt string转int
func StringToInt(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return i
}
// StringToInt64 string转int64
func StringToInt64(s string) int64 {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic(err)
}
return i
}
// Int64ToString int64转string
func Int64ToString(n int64) string {
return strconv.FormatInt(n, 10)
}
func mapToBytes(data map[string]interface{}) []byte {
bytes, _ := json.Marshal(data)
return bytes
}
// MapToStruct map转struct
func MapToStruct(data map[string]interface{}, v interface{}) {
_ = json.Unmarshal(mapToBytes(data), v)
}
// GetDirPath 获取目录路径
func GetDirPath(resType string) string {
sysType := runtime.GOOS
switch sysType {
case "linux":
if resType == "log" {
return config.AppCoreConfig.CuteGoConfig.File.Linux.Logs
} else if resType == "avatar" {
return config.AppCoreConfig.CuteGoConfig.File.Linux.Avatar
} else if resType == "file" {
return config.AppCoreConfig.CuteGoConfig.File.Linux.Path
}
break
case "windows":
if resType == "log" {
return config.AppCoreConfig.CuteGoConfig.File.Windows.Logs
} else if resType == "avatar" {
return config.AppCoreConfig.CuteGoConfig.File.Windows.Avatar
} else if resType == "file" {
return config.AppCoreConfig.CuteGoConfig.File.Windows.Path
}
break
case "mac":
if resType == "log" {
return config.AppCoreConfig.CuteGoConfig.File.Mac.Logs
} else if resType == "avatar" {
return config.AppCoreConfig.CuteGoConfig.File.Mac.Avatar
} else if resType == "file" {
return config.AppCoreConfig.CuteGoConfig.File.Mac.Path
}
break
case "darwin":
if resType == "log" {
return config.AppCoreConfig.CuteGoConfig.File.Mac.Logs
} else if resType == "avatar" {
return config.AppCoreConfig.CuteGoConfig.File.Mac.Avatar
} else if resType == "file" {
return config.AppCoreConfig.CuteGoConfig.File.Mac.Path
}
}
return config.AppCoreConfig.CuteGoConfig.File.Linux.Logs
}
// CreateAllDir 递归创建文件夹
func CreateAllDir(filePath string) error {
if !IsFileOrDirExist(filePath) {
err := os.MkdirAll(filePath, os.ModePerm)
if err != nil {
fmt.Println("创建文件夹失败, error info:", err)
return err
}
return err
}
return nil
}
// IsFileOrDirExist 判断所给路径文件/文件夹是否存在(返回true是存在)
func IsFileOrDirExist(path string) bool {
// os.Stat获取文件信息
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
// 类三元表达式
// condition 成立条件
// trueVal 当条件为true时返回
// false 当条件为false时返回
func If(condition bool, trueVal, falseVal interface{}) interface{} {
if condition {
return trueVal
}
return falseVal
}
// 结构体、Map等转Json字符串
// @Param v interface{}
// @Return Json字符串
func StructToJson(v interface{}) string {
jsonBytes, err := json.Marshal(&v)
if err != nil {
ErrorLog(err)
return ""
}
s := string(jsonBytes)
//DebugLogf("StructToJson, json=%s", s)
return s
}
// Json字符串转结构体、Map等
//
// 单个对象
// s := new(models2.SysConfig)
// return common.JsonToStruct(get, s).(*models2.SysConfig)
//
// 切片(interface{}.(期望类型))
// s := make([]interface {}, 0)
// target := common.JsonToStruct(get, s)
// target.([]dataobject.SysDictData)
//
// @Param data Json字符串
// @Param s 容器(结构体、Map等)
// @Return interface{}
func JsonToStruct(data string, s interface{}) interface{} {
err := json.Unmarshal([]byte(data), &s)
if err != nil {
ErrorLog(err)
return nil
}
DebugLogf("JsonToStruct, obj=%v", s)
return s
}
+111 -6
View File
@@ -2,10 +2,14 @@ package config
import (
config "cutego/pkg/config/models"
"cutego/pkg/logging"
"encoding/json"
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
"os"
"runtime"
"strconv"
)
var (
@@ -80,16 +84,117 @@ func readAppYmlFile(resourcePath string) {
LoadYamlFile(applicationEnvFilePath, AppEnvConfig)
}
// ExecuteTip 执行日志
func ExecuteTip(message string) {
fmt.Println(fmt.Sprintf("-------------------- %s --------------------", message))
// IntToString int转string
func IntToString(n int) string {
return strconv.Itoa(n)
}
// StringToInt string转int
func StringToInt(s string) int {
i, err := strconv.Atoi(s)
if err != nil {
panic(err)
}
return i
}
// StringToInt64 string转int64
func StringToInt64(s string) int64 {
i, err := strconv.ParseInt(s, 10, 64)
if err != nil {
panic(err)
}
return i
}
// Int64ToString int64转string
func Int64ToString(n int64) string {
return strconv.FormatInt(n, 10)
}
func mapToBytes(data map[string]interface{}) []byte {
bytes, _ := json.Marshal(data)
return bytes
}
// MapToStruct map转struct
func MapToStruct(data map[string]interface{}, v interface{}) {
_ = json.Unmarshal(mapToBytes(data), v)
}
// GetDirPath 获取目录路径
func GetDirPath(resType string) string {
sysType := runtime.GOOS
switch sysType {
case "linux":
if resType == "logging" {
return AppCoreConfig.CuteGoConfig.File.Linux.Logs
} else if resType == "avatar" {
return AppCoreConfig.CuteGoConfig.File.Linux.Avatar
} else if resType == "file" {
return AppCoreConfig.CuteGoConfig.File.Linux.Path
}
break
case "windows":
if resType == "logging" {
return AppCoreConfig.CuteGoConfig.File.Windows.Logs
} else if resType == "avatar" {
return AppCoreConfig.CuteGoConfig.File.Windows.Avatar
} else if resType == "file" {
return AppCoreConfig.CuteGoConfig.File.Windows.Path
}
break
case "mac":
if resType == "logging" {
return AppCoreConfig.CuteGoConfig.File.Mac.Logs
} else if resType == "avatar" {
return AppCoreConfig.CuteGoConfig.File.Mac.Avatar
} else if resType == "file" {
return AppCoreConfig.CuteGoConfig.File.Mac.Path
}
break
case "darwin":
if resType == "logging" {
return AppCoreConfig.CuteGoConfig.File.Mac.Logs
} else if resType == "avatar" {
return AppCoreConfig.CuteGoConfig.File.Mac.Avatar
} else if resType == "file" {
return AppCoreConfig.CuteGoConfig.File.Mac.Path
}
}
return AppCoreConfig.CuteGoConfig.File.Linux.Logs
}
// CreateAllDir 递归创建文件夹
func CreateAllDir(filePath string) error {
if !IsFileOrDirExist(filePath) {
err := os.MkdirAll(filePath, os.ModePerm)
if err != nil {
fmt.Println("创建文件夹失败, error info:", err)
return err
}
return err
}
return nil
}
// IsFileOrDirExist 判断所给路径文件/文件夹是否存在(返回true是存在)
func IsFileOrDirExist(path string) bool {
// os.Stat获取文件信息
_, err := os.Stat(path)
if err != nil {
if os.IsExist(err) {
return true
}
return false
}
return true
}
func init() {
// 资源文件所在的路径
resourcePath := GetRootPath()
ExecuteTip("初始化应用配置 start")
logging.InfoLog("application init start...")
readAppYmlFile(resourcePath)
ExecuteTip("初始化应用配置 end")
return
logging.InfoLog("application init start...")
}
+10 -10
View File
@@ -3,7 +3,7 @@ package cronjob
import (
"cutego/modules/core/job"
"cutego/modules/core/service"
"cutego/pkg/common"
"cutego/pkg/logging"
"github.com/robfig/cron"
)
@@ -23,24 +23,24 @@ var aliasCronMap = make(map[string]*cron.Cron)
// StopCronFunc 停止任务, 不会停止已开始的任务
func StopCronFunc(aliasName string) {
common.InfoLogf("停止任务 %s ---> Start", aliasName)
logging.InfoLogf("停止任务 %s ---> Start", aliasName)
go aliasCronMap[aliasName].Stop()
common.InfoLogf("停止任务 %s ---> Finish", aliasName)
logging.InfoLogf("停止任务 %s ---> Finish", aliasName)
}
// StartCronFunc 开始任务
func StartCronFunc(aliasName string) {
common.InfoLogf("唤起任务 %s ---> Start", aliasName)
logging.InfoLogf("唤起任务 %s ---> Start", aliasName)
go aliasCronMap[aliasName].Start()
common.InfoLogf("唤起任务 %s ---> Finish", aliasName)
logging.InfoLogf("唤起任务 %s ---> Finish", aliasName)
}
// RemoveCronFunc 移除任务
func RemoveCronFunc(aliasName string) {
common.InfoLogf("移除任务 %s ---> Start", aliasName)
logging.InfoLogf("移除任务 %s ---> Start", aliasName)
go StopCronFunc(aliasName)
delete(aliasCronMap, aliasName)
common.InfoLogf("移除任务 %s ---> Finish", aliasName)
logging.InfoLogf("移除任务 %s ---> Finish", aliasName)
}
// AppendCronFunc 新增任务
@@ -49,7 +49,7 @@ func AppendCronFunc(jobCron string, aliasName string, status string) {
aliasCronMap[aliasName].Stop()
aliasCronMap[aliasName] = nil
}
common.InfoLogf("新增任务 %s ---> Start", aliasName)
logging.InfoLogf("新增任务 %s ---> Start", aliasName)
c := cron.New()
err := c.AddFunc(jobCron, job.AliasFuncMap[aliasName])
if err != nil {
@@ -59,10 +59,10 @@ func AppendCronFunc(jobCron string, aliasName string, status string) {
go func() {
c.Start()
aliasCronMap[aliasName] = c
common.InfoLogf("调度定时任务 --- %s ---> Success", aliasName)
logging.InfoLogf("调度定时任务 --- %s ---> Success", aliasName)
}()
}
common.InfoLogf("新增任务 %s ---> Finish", aliasName)
logging.InfoLogf("新增任务 %s ---> Finish", aliasName)
}
func init() {
+3 -2
View File
@@ -4,16 +4,16 @@ import (
"cutego/modules/core/router"
"cutego/pkg/filter"
"cutego/pkg/jwt"
"cutego/pkg/logging"
"cutego/pkg/middleware"
"cutego/pkg/middleware/logger"
"cutego/pkg/websocket"
"cutego/refs"
"fmt"
"github.com/gin-gonic/gin"
)
func init() {
fmt.Println("CoolGin init...")
logging.InfoLog("CoolGin init start...")
refs.CoolGin = gin.New()
refs.CoolGin.Use(gin.Logger())
refs.CoolGin.Use(gin.Recovery())
@@ -27,4 +27,5 @@ func init() {
v1Router := refs.CoolGin.Group("/api/v1")
// 加载: 模块路由
router.LoadCoreRouter(v1Router)
logging.InfoLog("CoolGin init end...")
}
+1 -1
View File
@@ -1,4 +1,4 @@
package common
package logging
import "github.com/druidcaesa/gotool"
+5 -4
View File
@@ -3,6 +3,7 @@ package logger
import (
"cutego/pkg/common"
"cutego/pkg/config"
"cutego/pkg/logging"
"fmt"
"github.com/druidcaesa/gotool"
"github.com/gin-gonic/gin"
@@ -16,18 +17,18 @@ import (
// LoggerToFile 日志记录到文件
func LoggerToFile() gin.HandlerFunc {
dirPath := common.GetDirPath("log")
fileName := path.Join(dirPath, "application.log")
dirPath := common.GetDirPath("logging")
fileName := path.Join(dirPath, "application.logging")
if !common.IsFileOrDirExist(dirPath) {
err := common.CreateAllDir(dirPath)
if err != nil {
common.ErrorLog(err)
logging.ErrorLog(err)
}
}
if !gotool.FileUtils.Exists(fileName) {
create, err := os.Create(fileName)
if err != nil {
common.ErrorLog(err)
logging.ErrorLog(err)
}
defer create.Close()
}
+2 -2
View File
@@ -1,7 +1,7 @@
package middleware
import (
"cutego/pkg/common"
"cutego/pkg/logging"
"github.com/gin-gonic/gin"
"net/http"
"runtime/debug"
@@ -10,7 +10,7 @@ import (
func Recover(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
common.ErrorLog("panic: %v\n", r)
logging.ErrorLog("panic: %v\n", r)
debug.PrintStack()
c.JSON(http.StatusOK, gin.H{
"code": http.StatusInternalServerError,
+2 -2
View File
@@ -1,7 +1,7 @@
package page
import (
"cutego/pkg/common"
"cutego/pkg/logging"
"github.com/go-xorm/xorm"
)
@@ -34,7 +34,7 @@ func GetTotal(engine *xorm.Session, args ...interface{}) (int64, error) {
}
count, err := engine.Count()
if err != nil {
common.ErrorLog(err.Error())
logging.ErrorLog(err.Error())
return 0, err
}
return count, nil
+6 -5
View File
@@ -3,6 +3,7 @@ package redispool
import (
"cutego/pkg/common"
"cutego/pkg/config"
"cutego/pkg/logging"
"fmt"
"github.com/druidcaesa/gotool"
"github.com/gomodule/redigo/redis"
@@ -41,19 +42,19 @@ func newPool() *redis.Pool {
Dial: func() (redis.Conn, error) {
c, err := redis.Dial("tcp", fmt.Sprintf("%s:%d", config.AppEnvConfig.Redis.Host, config.AppEnvConfig.Redis.Port))
if err != nil {
common.FatalfLog("Redis.Dial: %v", err)
logging.FatalfLog("Redis.Dial: %v", err)
return nil, err
}
if gotool.StrUtils.HasNotEmpty(config.AppEnvConfig.Redis.Password) {
if _, err := c.Do("AUTH", config.AppEnvConfig.Redis.Password); err != nil {
c.Close()
common.FatalfLog("Redis.AUTH: %v", err)
logging.FatalfLog("Redis.AUTH: %v", err)
return nil, err
}
}
if _, err := c.Do("SELECT", config.AppEnvConfig.Redis.Database); err != nil {
c.Close()
common.FatalfLog("Redis.SELECT: %v", err)
logging.FatalfLog("Redis.SELECT: %v", err)
return nil, err
}
return c, nil
@@ -91,11 +92,11 @@ func (r *RedisClient) loopRead() {
if len(it.Key) > 0 {
if len(it.Field) > 0 {
if _, err := r.HSET(it.Key, it.Field, it.Value); err != nil {
common.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error())
logging.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error())
}
} else {
if _, err := r.SET(it.Key, it.Value); err != nil {
common.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error())
logging.DebugLogf("[%s, %s, %s]: %s\n", it.Key, it.Field, it.Value, err.Error())
}
}
if it.Expire > 0 {
+43
View File
@@ -1,5 +1,10 @@
package util
import (
"cutego/pkg/logging"
"encoding/json"
)
// IF 三元表达式
func IF(condition bool, trueValue interface{}, falseValue interface{}) interface{} {
if condition {
@@ -7,3 +12,41 @@ func IF(condition bool, trueValue interface{}, falseValue interface{}) interface
}
return falseValue
}
// 结构体、Map等转Json字符串
// @Param v interface{}
// @Return Json字符串
func StructToJson(v interface{}) string {
jsonBytes, err := json.Marshal(&v)
if err != nil {
logging.ErrorLog(err)
return ""
}
s := string(jsonBytes)
//DebugLogf("StructToJson, json=%s", s)
return s
}
// Json字符串转结构体、Map等
//
// 单个对象
// s := new(models2.SysConfig)
// return common.JsonToStruct(get, s).(*models2.SysConfig)
//
// 切片(interface{}.(期望类型))
// s := make([]interface {}, 0)
// target := common.JsonToStruct(get, s)
// target.([]dataobject.SysDictData)
//
// @Param data Json字符串
// @Param s 容器(结构体、Map等)
// @Return interface{}
func JsonToStruct(data string, s interface{}) interface{} {
err := json.Unmarshal([]byte(data), &s)
if err != nil {
logging.ErrorLog(err)
return nil
}
//common.DebugLogf("JsonToStruct, obj=%v", s)
return s
}
+2 -2
View File
@@ -2,7 +2,7 @@ package util
import (
"bytes"
"cutego/pkg/common"
"cutego/pkg/logging"
"encoding/gob"
)
@@ -21,7 +21,7 @@ func DeepCopy(src, dst interface{}) interface{} {
}
err := gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst)
if err != nil {
common.ErrorLogf("src(%v)---> dst(%v), error", src, dst)
logging.ErrorLogf("src(%v)---> dst(%v), error", src, dst)
}
return dst
}
+3 -3
View File
@@ -3,9 +3,9 @@ package util
import (
"cutego/modules/core/api/v1/response"
"cutego/modules/core/dataobject"
"cutego/pkg/common"
"cutego/pkg/config"
"cutego/pkg/jwt"
"cutego/pkg/logging"
"cutego/refs"
"github.com/gin-gonic/gin"
"strings"
@@ -21,7 +21,7 @@ func GetUserInfo(c *gin.Context) *response.UserResponse {
// parseToken 解析token包含的信息
claims, err := jwt.ParseToken(s[1])
if err != nil {
common.ErrorLog(err)
logging.ErrorLog(err)
}
info := claims.UserInfo
return &info
@@ -34,7 +34,7 @@ func CheckLockToken(c *gin.Context) bool {
info := GetUserInfo(c)
get, err := refs.RedisDB.GET(info.UserName)
if err != nil {
common.ErrorLog(err)
logging.ErrorLog(err)
return false
}
token := c.Request.Header.Get(config.AppEnvConfig.Jwt.Header)
+6 -6
View File
@@ -1,7 +1,7 @@
package websocket
import (
"cutego/pkg/common"
"cutego/pkg/logging"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"net/http"
@@ -12,16 +12,16 @@ import (
// var ws = new WebSocket("ws://127.0.0.1:21366/websocket?user=admin&code=notice");
// // 连接打开时触发
// ws.onopen = function(evt) {
// console.log("Connection open ...");
// console.logging("Connection open ...");
// ws.send("Hello WebSockets!");
// };
// // 接收到消息时触发
// ws.onmessage = function(evt) {
// console.log("Received Message: " + evt.data);
// console.logging("Received Message: " + evt.data);
// };
// // 连接关闭时触发
// ws.onclose = function(evt) {
// console.log("Connection closed.");
// console.logging("Connection closed.");
// };
// </script>
@@ -69,8 +69,8 @@ func HandleWebSocketMessage(c *gin.Context) {
// 回调函数的具体实现
func HandleAdminNotice(messageType int, content []byte) error {
common.InfoLog("messageType=%d\n", messageType)
common.InfoLog("content=%s\n", string(content))
logging.InfoLog("messageType=%d\n", messageType)
logging.InfoLog("content=%s\n", string(content))
return nil
}