This commit is contained in:
2025-06-23 13:39:19 +08:00
parent b93897f0a4
commit 32a7a512a2
8 changed files with 276 additions and 218 deletions

View File

@@ -1,91 +1,91 @@
package cool
import (
"context"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/i18n/gi18n"
"github.com/gogf/gf/v2/os/gbuild"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/guid"
"gorm.io/gorm"
)
var (
GormDBS = make(map[string]*gorm.DB) // 定义全局gorm.DB对象集合 仅供内部使用
CacheEPS = gcache.New() // 定义全局缓存对象 供EPS使用
CacheManager = gcache.New() // 定义全局缓存对象 供其他业务使用
ProcessFlag = guid.S() // 定义全局进程标识
RunMode = "dev" // 定义全局运行模式
IsRedisMode = false // 定义全局是否为redis模式
I18n = gi18n.New() // 定义全局国际化对象
)
func init() {
var (
ctx = gctx.GetInitCtx()
redisConfig = &gredis.Config{}
)
g.Log().Debug(ctx, "module cool init start ...")
buildData := gbuild.Data()
if _, ok := buildData["mode"]; ok {
RunMode = buildData["mode"].(string)
}
if RunMode == "cool-tools" {
return
}
redisVar, err := g.Cfg().Get(ctx, "redis.cool")
if err != nil {
g.Log().Error(ctx, "初始化缓存失败,请检查配置文件")
panic(err)
}
if !redisVar.IsEmpty() {
redisVar.Struct(redisConfig)
redis, err := gredis.New(redisConfig)
if err != nil {
panic(err)
}
CacheManager.SetAdapter(gcache.NewAdapterRedis(redis))
IsRedisMode = true
}
g.Log().Debug(ctx, "当前运行模式", RunMode)
g.Log().Debug(ctx, "当前实例ID:", ProcessFlag)
g.Log().Debug(ctx, "是否缓存模式:", IsRedisMode)
g.Log().Debug(ctx, "module cool init finished ...")
}
// cool.OK 正常返回
type BaseRes struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// 返回正常结果
func Ok(data interface{}) *BaseRes {
return &BaseRes{
Code: 1000,
Message: I18n.Translate(context.TODO(), "BaseResMessage"),
Data: data,
}
}
// 失败返回结果
func Fail(message string) *BaseRes {
return &BaseRes{
Code: 1001,
Message: message,
}
}
// 分布式函数
// func DistributedFunc(ctx g.Ctx, f func(ctx g.Ctx) (interface{}, error)) (interface{}, error) {
// if ProcessFlag == ctx.Request.Header.Get("processFlag") {
// return f(ctx)
// }
// return nil, nil
// }
package cool
import (
"context"
"github.com/gogf/gf/v2/database/gredis"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/i18n/gi18n"
"github.com/gogf/gf/v2/os/gbuild"
"github.com/gogf/gf/v2/os/gcache"
"github.com/gogf/gf/v2/os/gctx"
"github.com/gogf/gf/v2/util/guid"
"gorm.io/gorm"
)
var (
GormDBS = make(map[string]*gorm.DB) // 定义全局gorm.DB对象集合 仅供内部使用
CacheEPS = gcache.New() // 定义全局缓存对象 供EPS使用
CacheManager = gcache.New() // 定义全局缓存对象 供其他业务使用
ProcessFlag = guid.S() // 定义全局进程标识
RunMode = "dev" // 定义全局运行模式
IsRedisMode = false // 定义全局是否为redis模式
I18n = gi18n.New() // 定义全局国际化对象
)
func init() {
var (
ctx = gctx.GetInitCtx()
redisConfig = &gredis.Config{}
)
g.Log().Debug(ctx, "module cool init start ...")
buildData := gbuild.Data()
if _, ok := buildData["mode"]; ok {
RunMode = buildData["mode"].(string)
}
if RunMode == "cool-tools" {
return
}
redisVar, err := g.Cfg().Get(ctx, "redis.cool")
if err != nil {
g.Log().Error(ctx, "初始化缓存失败,请检查配置文件")
panic(err)
}
if !redisVar.IsEmpty() {
redisVar.Struct(redisConfig)
redis, err := gredis.New(redisConfig)
if err != nil {
panic(err)
}
CacheManager.SetAdapter(gcache.NewAdapterRedis(redis))
IsRedisMode = true
}
g.Log().Debug(ctx, "当前运行模式", RunMode)
g.Log().Debug(ctx, "当前实例ID:", ProcessFlag)
g.Log().Debug(ctx, "是否缓存模式:", IsRedisMode)
g.Log().Debug(ctx, "module cool init finished ...")
}
// cool.OK 正常返回
type BaseRes struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
}
// 返回正常结果
func Ok(data interface{}) *BaseRes {
return &BaseRes{
Code: 1000,
Message: I18n.Translate(context.TODO(), "BaseResMessage"),
Data: data,
}
}
// 失败返回结果
func Fail(message string) *BaseRes {
return &BaseRes{
Code: 1001,
Message: message,
}
}
// 分布式函数
// func DistributedFunc(ctx g.Ctx, f func(ctx g.Ctx) (interface{}, error)) (interface{}, error) {
// if ProcessFlag == ctx.Request.Header.Get("processFlag") {
// return f(ctx)
// }
// return nil, nil
// }

View File

@@ -1,64 +1,70 @@
package coolconfig
import "github.com/gogf/gf/v2/frame/g"
// cool config
type sConfig struct {
AutoMigrate bool `json:"auto_migrate,omitempty"` // 是否自动创建表
Eps bool `json:"eps,omitempty"` // 是否开启eps
File *file `json:"file,omitempty"` // 文件上传配置
}
// OSS相关配置
type oss struct {
Endpoint string `json:"endpoint"`
AccessKeyID string `json:"accessKeyID"`
SecretAccessKey string `json:"secretAccessKey"`
UseSSL bool `json:"useSSL"`
BucketName string `json:"bucketName"`
Location string `json:"location"`
}
// 文件上传配置
type file struct {
Mode string `json:"mode"` // 模式 local oss
Domain string `json:"domain"` // 域名 http://
Oss *oss `json:"oss,omitempty"`
}
// NewConfig new config
func newConfig() *sConfig {
var ctx g.Ctx
config := &sConfig{
AutoMigrate: GetCfgWithDefault(ctx, "cool.autoMigrate", g.NewVar(false)).Bool(),
Eps: GetCfgWithDefault(ctx, "cool.eps", g.NewVar(false)).Bool(),
File: &file{
Mode: GetCfgWithDefault(ctx, "cool.file.mode", g.NewVar("none")).String(),
Domain: GetCfgWithDefault(ctx, "cool.file.domain", g.NewVar("http://127.0.0.1:8300")).String(),
Oss: &oss{
Endpoint: GetCfgWithDefault(ctx, "cool.file.oss.endpoint", g.NewVar("127.0.0.1:9000")).String(),
AccessKeyID: GetCfgWithDefault(ctx, "cool.file.oss.accessKeyID", g.NewVar("")).String(),
SecretAccessKey: GetCfgWithDefault(ctx, "cool.file.oss.secretAccessKey", g.NewVar("")).String(),
UseSSL: GetCfgWithDefault(ctx, "cool.file.oss.useSSL", g.NewVar(false)).Bool(),
BucketName: GetCfgWithDefault(ctx, "cool.file.oss.bucketName", g.NewVar("cool-admin-go")).String(),
Location: GetCfgWithDefault(ctx, "cool.file.oss.location", g.NewVar("us-east-1")).String(),
},
},
}
return config
}
// Config config
var Config = newConfig()
// GetCfgWithDefault get config with default value
func GetCfgWithDefault(ctx g.Ctx, key string, defaultValue *g.Var) *g.Var {
value, err := g.Cfg().GetWithEnv(ctx, key)
if err != nil {
return defaultValue
}
if value.IsEmpty() || value.IsNil() {
return defaultValue
}
return value
}
package coolconfig
import "github.com/gogf/gf/v2/frame/g"
// cool config
type sConfig struct {
AutoMigrate bool `json:"auto_migrate,omitempty"` // 是否自动创建表
Eps bool `json:"eps,omitempty"` // 是否开启eps
File *file `json:"file,omitempty"` // 文件上传配置
Name string `json:"name"` // 项目名称
Port string `json:"port"`
PortBL string `json:"port_bl"`
}
// OSS相关配置
type oss struct {
Endpoint string `json:"endpoint"`
AccessKeyID string `json:"accessKeyID"`
SecretAccessKey string `json:"secretAccessKey"`
UseSSL bool `json:"useSSL"`
BucketName string `json:"bucketName"`
Location string `json:"location"`
}
// 文件上传配置
type file struct {
Mode string `json:"mode"` // 模式 local oss
Domain string `json:"domain"` // 域名 http://
Oss *oss `json:"oss,omitempty"`
}
// NewConfig new config
func newConfig() *sConfig {
var ctx g.Ctx
config := &sConfig{
AutoMigrate: GetCfgWithDefault(ctx, "blazing.autoMigrate", g.NewVar(false)).Bool(),
Name: GetCfgWithDefault(ctx, "server.name", g.NewVar("")).String(),
Eps: GetCfgWithDefault(ctx, "blazing.eps", g.NewVar(false)).Bool(),
Port: string(GetCfgWithDefault(ctx, "server.port", g.NewVar("8080")).String()),
PortBL: string(GetCfgWithDefault(ctx, "blazing.port", g.NewVar("8080")).String()),
File: &file{
Mode: GetCfgWithDefault(ctx, "blazing.file.mode", g.NewVar("none")).String(),
Domain: GetCfgWithDefault(ctx, "blazing.file.domain", g.NewVar("http://127.0.0.1:8300")).String(),
Oss: &oss{
Endpoint: GetCfgWithDefault(ctx, "blazing.file.oss.endpoint", g.NewVar("127.0.0.1:9000")).String(),
AccessKeyID: GetCfgWithDefault(ctx, "blazing.file.oss.accessKeyID", g.NewVar("")).String(),
SecretAccessKey: GetCfgWithDefault(ctx, "blazing.file.oss.secretAccessKey", g.NewVar("")).String(),
UseSSL: GetCfgWithDefault(ctx, "blazing.file.oss.useSSL", g.NewVar(false)).Bool(),
BucketName: GetCfgWithDefault(ctx, "blazing.file.oss.bucketName", g.NewVar("blazing")).String(),
Location: GetCfgWithDefault(ctx, "blazing.file.oss.location", g.NewVar("us-east-1")).String(),
},
},
}
return config
}
// Config config
var Config = newConfig()
// GetCfgWithDefault get config with default value
func GetCfgWithDefault(ctx g.Ctx, key string, defaultValue *g.Var) *g.Var {
value, err := g.Cfg().GetWithEnv(ctx, key)
if err != nil {
return defaultValue
}
if value.IsEmpty() || value.IsNil() {
return defaultValue
}
return value
}

View File

@@ -26,7 +26,7 @@ func main() {
if cool.IsRedisMode {
go cool.ListenFunc(gctx.New())
}
Start("27777") //注入service
Start(cool.Config.PortBL) //注入service
}
func Start(port string) {

View File

@@ -1,38 +1,39 @@
package cmd
import (
"context"
"blazing/cool"
i18n "blazing/modules/base/middleware"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
)
var (
Main = gcmd.Command{
Name: "main",
Usage: "main",
Brief: "start http server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
// g.Dump(g.DB("test").GetConfig())
if cool.IsRedisMode {
go cool.ListenFunc(ctx)
}
s := g.Server()
// 如果存在 data/cool-admin-vue/dist 目录,则设置为主目录
if gfile.IsDir("frontend/dist") {
s.SetServerRoot("frontend/dist")
}
// i18n 信息
s.BindHandler("/i18n", i18n.I18nInfo)
s.Run()
return nil
},
}
)
package cmd
import (
"context"
"blazing/cool"
i18n "blazing/modules/base/middleware"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/os/gcmd"
"github.com/gogf/gf/v2/os/gfile"
)
var (
Main = gcmd.Command{
Name: "main",
Usage: "main",
Brief: "start http server",
Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
// g.Dump(g.DB("test").GetConfig())
if cool.IsRedisMode {
go cool.ListenFunc(ctx)
}
s := g.Server()
s.SetServerAgent(cool.Config.Name)
// 如果存在 data/cool-admin-vue/dist 目录,则设置为主目录
if gfile.IsDir("public") {
s.SetServerRoot("public")
}
// i18n 信息
s.BindHandler("/i18n", i18n.I18nInfo)
s.Run()
return nil
},
}
)

View File

@@ -1,9 +1,14 @@
package main
import (
"fmt"
_ "github.com/gogf/gf/contrib/nosql/redis/v2"
"blazing/common/socket"
"blazing/common/socket/handler"
_ "blazing/contrib/files/local"
"blazing/cool"
// Minio按需启用
// _ "blazing/contrib/files/minio"
@@ -25,6 +30,22 @@ import (
)
func main() {
// gres.Dump()
go Start(cool.Config.Port)
cmd.Main.Run(gctx.New())
}
func Start(port string) {
head := handler.NewTomeeHandler()
head.Callback = recv
socket.NewServer(socket.WithPort(port), socket.WithSocketHandler(head)).Start()
}
func recv(data handler.TomeeHeader) {
fmt.Println(data)
// 处理接收到的TomeeHeader数据
// fmt.Println("收到数据:", data)
//processWithReflection(data)
}

View File

@@ -1,5 +1,7 @@
server:
address: ":8001"
name: "blazing server"
address: ":8080" #前台服务器地址
port: 12345
openapiPath: "/api.json"
swaggerPath: "/swagger"
clientMaxBodySize: 104857600 # 100MB in bytes 100*1024*1024
@@ -48,7 +50,8 @@ redis:
pass: 154252
cool:
blazing:
port: 27777
autoMigrate: true
eps: true
file:

View File

@@ -1,21 +1,44 @@
package middleware
import (
"blazing/modules/base/config"
"github.com/gogf/gf/v2/frame/g"
)
func init() {
if config.Config.Middleware.Authority.Enable {
g.Server().BindMiddleware("/admin/*/open/*", BaseAuthorityMiddlewareOpen)
g.Server().BindMiddleware("/admin/*/comm/*", BaseAuthorityMiddlewareComm)
g.Server().BindMiddleware("/admin/*", BaseAuthorityMiddleware)
g.Server().BindMiddleware("/*", AutoI18n)
}
if config.Config.Middleware.Log.Enable {
g.Server().BindMiddleware("/admin/*", BaseLog)
}
}
package middleware
import (
"blazing/modules/base/config"
"fmt"
"net/http"
"github.com/gogf/gf/v2/frame/g"
"github.com/gogf/gf/v2/net/ghttp"
)
func MiddlewareCORS(r *ghttp.Request) {
r.Response.CORSDefault()
corsOptions := r.Response.DefaultCORSOptions()
corsOptions.AllowDomain = []string{"*"}
if !r.Response.CORSAllowedOrigin(corsOptions) {
r.Response.WriteStatus(http.StatusForbidden)
return
}
r.Response.CORS(corsOptions)
if r.Response.Request.Method == "OPTIONS" {
r.Response.WriteStatus(http.StatusOK)
return
}
fmt.Println(r.Response.Header())
//g.Dump(r.Response.Server.SetConfig(gtt))
//r.Response.Header().Del("Server") // 删除Server头
// r.Response.Header().Set("Server", "blazing")
r.Middleware.Next()
}
func init() {
if config.Config.Middleware.Authority.Enable {
g.Server().BindMiddleware("/admin/*/open/*", BaseAuthorityMiddlewareOpen)
g.Server().BindMiddleware("/admin/*/comm/*", BaseAuthorityMiddlewareComm)
g.Server().BindMiddleware("/admin/*", BaseAuthorityMiddleware)
g.Server().BindMiddleware("/*", AutoI18n)
g.Server().BindMiddleware("/*", MiddlewareCORS)
}
if config.Config.Middleware.Log.Enable {
g.Server().BindMiddleware("/admin/*", BaseLog)
}
}

4
public/crossdomain.xml Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>