refactor: 引入tailwind css & 后端部分非公共包位置调整

This commit is contained in:
meilin.huang
2025-04-18 22:07:37 +08:00
parent 585cbbed23
commit abd2b4bac0
168 changed files with 763 additions and 793 deletions

View File

@@ -9,7 +9,7 @@ require (
github.com/emirpasic/gods v1.18.1
github.com/gin-gonic/gin v1.10.0
github.com/glebarez/sqlite v1.11.0
github.com/go-gormigrate/gormigrate/v2 v2.1.3
github.com/go-gormigrate/gormigrate/v2 v2.1.4
github.com/go-ldap/ldap/v3 v3.4.8
github.com/go-playground/locales v0.14.1
github.com/go-playground/universal-translator v0.18.1

View File

@@ -2,46 +2,33 @@ package initialize
import (
"fmt"
"io/fs"
"mayfly-go/pkg/config"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/middleware"
"mayfly-go/pkg/req"
"mayfly-go/static"
"net/http"
"reflect"
"github.com/gin-gonic/gin"
)
// RouterApi
// 该接口的实现类注册到ioc中则会自动将请求配置注册到路由中
type RouterApi interface {
// ReqConfs 获取请求配置信息
ReqConfs() *req.Confs
}
func InitRouter() *gin.Engine {
// server配置
serverConfig := config.Conf.Server
gin.SetMode(serverConfig.Model)
var router = gin.New()
router.MaxMultipartMemory = 8 << 20
type RouterConfig struct {
ContextPath string // 请求路径上下文
}
func InitRouter(router *gin.Engine, conf RouterConfig) *gin.Engine {
// 没有路由即 404返回
router.NoRoute(func(g *gin.Context) {
g.JSON(http.StatusNotFound, gin.H{"code": 404, "msg": fmt.Sprintf("not found '%s:%s'", g.Request.Method, g.Request.URL.Path)})
})
// 设置静态资源
setStatic(serverConfig.ContextPath, router)
// 是否允许跨域
if serverConfig.Cors {
router.Use(middleware.Cors())
}
// 设置路由组
api := router.Group(serverConfig.ContextPath + "/api")
api := router.Group(conf.ContextPath + "/api")
// 获取所有实现了RouterApi接口的实例并注册对应路由
ras := ioc.GetBeansByType[RouterApi](reflect.TypeOf((*RouterApi)(nil)).Elem())
@@ -56,36 +43,3 @@ func InitRouter() *gin.Engine {
return router
}
func setStatic(contextPath string, router *gin.Engine) {
// 使用embed打包静态资源至二进制文件中
fsys, _ := fs.Sub(static.Static, "static")
fileServer := http.FileServer(http.FS(fsys))
handler := WrapStaticHandler(http.StripPrefix(contextPath, fileServer))
router.GET(contextPath+"/", handler)
router.GET(contextPath+"/favicon.ico", handler)
router.GET(contextPath+"/config.js", handler)
// 所有/assets/**开头的都是静态资源文件
router.GET(contextPath+"/assets/*file", handler)
// 设置静态资源
if staticConfs := config.Conf.Server.Static; staticConfs != nil {
for _, scs := range *staticConfs {
router.StaticFS(scs.RelativePath, http.Dir(scs.Root))
}
}
// 设置静态文件
if staticFileConfs := config.Conf.Server.StaticFile; staticFileConfs != nil {
for _, sfs := range *staticFileConfs {
router.StaticFile(sfs.RelativePath, sfs.Filepath)
}
}
}
func WrapStaticHandler(h http.Handler) gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Cache-Control", `public, max-age=31536000`)
h.ServeHTTP(c.Writer, c.Request)
}
}

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -1,13 +1,13 @@
package api
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/db/api/form"
"mayfly-go/internal/db/api/vo"
"mayfly-go/internal/db/application"
"mayfly-go/internal/db/application/dto"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/imsg"
"mayfly-go/internal/pkg/consts"
tagapp "mayfly-go/internal/tag/application"
tagentity "mayfly-go/internal/tag/domain/entity"

View File

@@ -2,13 +2,13 @@ package application
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/db/application/dto"
"mayfly-go/internal/db/dbm"
"mayfly-go/internal/db/dbm/dbi"
"mayfly-go/internal/db/domain/entity"
"mayfly-go/internal/db/domain/repository"
"mayfly-go/internal/db/imsg"
"mayfly-go/internal/pkg/consts"
tagapp "mayfly-go/internal/tag/application"
tagdto "mayfly-go/internal/tag/application/dto"
tagentity "mayfly-go/internal/tag/domain/entity"

View File

@@ -2,7 +2,6 @@ package dbm
import (
"fmt"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/db/dbm/dbi"
_ "mayfly-go/internal/db/dbm/dm"
_ "mayfly-go/internal/db/dbm/mssql"
@@ -11,6 +10,7 @@ import (
_ "mayfly-go/internal/db/dbm/postgres"
_ "mayfly-go/internal/db/dbm/sqlite"
"mayfly-go/internal/machine/mcm"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/cache"
"mayfly-go/pkg/logx"
"sync"

View File

@@ -2,8 +2,8 @@ package sqlparser
import (
"io"
"mayfly-go/internal/common/utils"
"mayfly-go/internal/db/dbm/sqlparser/sqlstmt"
"mayfly-go/internal/pkg/utils"
)
type DbDialect string

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -2,7 +2,6 @@ package api
import (
"fmt"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/flow/api/form"
"mayfly-go/internal/flow/api/vo"
"mayfly-go/internal/flow/application"
@@ -10,6 +9,7 @@ import (
"mayfly-go/internal/flow/domain/entity"
"mayfly-go/internal/flow/domain/repository"
"mayfly-go/internal/flow/imsg"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils/collx"

View File

@@ -9,6 +9,7 @@ import (
"mayfly-go/internal/flow/domain/repository"
"mayfly-go/internal/flow/imsg"
msgdto "mayfly-go/internal/msg/application/dto"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/base"
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
@@ -108,7 +109,7 @@ func (p *procinstAppImpl) CancelProc(ctx context.Context, procinstId uint64) err
if la == nil {
return errorx.NewBiz("no login")
}
if procinst.CreatorId != la.Id {
if procinst.CreatorId != consts.AdminId && procinst.CreatorId != la.Id {
return errorx.NewBizI(ctx, imsg.ErrProcinstCancelSelf)
}
procinst.Status = entity.ProcinstStatusCancelled

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -2,7 +2,6 @@ package api
import (
"fmt"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/event"
"mayfly-go/internal/machine/api/form"
"mayfly-go/internal/machine/api/vo"
@@ -12,6 +11,7 @@ import (
"mayfly-go/internal/machine/guac"
"mayfly-go/internal/machine/imsg"
"mayfly-go/internal/machine/mcm"
"mayfly-go/internal/pkg/consts"
tagapp "mayfly-go/internal/tag/application"
tagentity "mayfly-go/internal/tag/domain/entity"
"mayfly-go/pkg/biz"

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -2,7 +2,7 @@ package mcm
import (
"errors"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
tagentity "mayfly-go/internal/tag/domain/entity"
"mayfly-go/pkg/cache"
"mayfly-go/pkg/logx"

View File

@@ -2,13 +2,13 @@ package api
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/event"
"mayfly-go/internal/mongo/api/form"
"mayfly-go/internal/mongo/api/vo"
"mayfly-go/internal/mongo/application"
"mayfly-go/internal/mongo/domain/entity"
"mayfly-go/internal/mongo/imsg"
"mayfly-go/internal/pkg/consts"
tagapp "mayfly-go/internal/tag/application"
tagentity "mayfly-go/internal/tag/domain/entity"
"mayfly-go/pkg/biz"

View File

@@ -2,11 +2,11 @@ package application
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/mongo/domain/entity"
"mayfly-go/internal/mongo/domain/repository"
"mayfly-go/internal/mongo/imsg"
"mayfly-go/internal/mongo/mgm"
"mayfly-go/internal/pkg/consts"
tagapp "mayfly-go/internal/tag/application"
tagdto "mayfly-go/internal/tag/application/dto"
tagentity "mayfly-go/internal/tag/domain/entity"

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -1,8 +1,8 @@
package mgm
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/machine/mcm"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/cache"
"mayfly-go/pkg/logx"
"sync"

View File

@@ -75,8 +75,7 @@ func (m *MsgTmpl) DelMsgTmpls(rc *req.Ctx) {
func (m *MsgTmpl) SendMsg(rc *req.Ctx) {
code := rc.PathParam("code")
form := &form.SendMsg{}
req.BindJsonAndValid(rc, form)
form := req.BindJsonAndValid(rc, new(form.SendMsg))
rc.ReqParam = form

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -2,7 +2,7 @@ package starter
import (
"fmt"
"mayfly-go/pkg/config"
"mayfly-go/internal/pkg/config"
"mayfly-go/pkg/logx"
"os"
"runtime/debug"

View File

@@ -2,7 +2,7 @@ package starter
import (
"log"
"mayfly-go/pkg/config"
"mayfly-go/internal/pkg/config"
"mayfly-go/pkg/global"
"mayfly-go/pkg/logx"
"time"

View File

@@ -3,7 +3,7 @@ package starter
import (
"context"
"fmt"
"mayfly-go/pkg/config"
"mayfly-go/internal/pkg/config"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/rediscli"

View File

@@ -3,8 +3,8 @@ package starter
import (
"context"
"mayfly-go/initialize"
"mayfly-go/internal/pkg/config"
"mayfly-go/migration"
"mayfly-go/pkg/config"
"mayfly-go/pkg/global"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/validatorx"
@@ -43,6 +43,8 @@ func RunWebServer() {
// 参数校验器初始化、如错误提示中文转译等
validatorx.Init()
// 注册自定义正则表达式校验规则
RegisterCustomPatterns()
// 初始化其他需要启动时运行的方法
initialize.InitOther()
@@ -50,3 +52,10 @@ func RunWebServer() {
// 运行web服务
runWebServer(ctx)
}
// 注册自定义正则表达式校验规则
func RegisterCustomPatterns() {
// 账号用户名校验
validatorx.RegisterPattern("account_username", "^[a-zA-Z0-9_]{5,20}$", "只允许输入5-20位大小写字母、数字、下划线")
validatorx.RegisterPattern("resource_code", "^[a-zA-Z0-9_\\-.:]{1,32}$", "只允许输入1-32位大小写字母、数字、_-.:")
}

View File

@@ -0,0 +1,126 @@
package starter
import (
"context"
"errors"
"io/fs"
"mayfly-go/initialize"
"mayfly-go/internal/pkg/config"
"mayfly-go/pkg/i18n"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/middleware"
"mayfly-go/pkg/req"
"mayfly-go/static"
"net/http"
"time"
sysapp "mayfly-go/internal/sys/application"
"github.com/gin-gonic/gin"
)
func runWebServer(ctx context.Context) {
// 设置gin日志输出器
logOut := logx.GetConfig().GetLogOut()
gin.DefaultErrorWriter = logOut
gin.DefaultWriter = logOut
// 权限处理器
req.UseBeforeHandlerInterceptor(req.PermissionHandler)
// 日志处理器
req.UseAfterHandlerInterceptor(req.LogHandler)
// 设置日志保存函数
req.SetSaveLogFunc(sysapp.GetSyslogApp().SaveFromReq)
// jwt配置
jwtConf := config.Conf.Jwt
req.SetJwtConf(req.JwtConf{
Key: jwtConf.Key,
ExpireTime: jwtConf.ExpireTime,
RefreshTokenExpireTime: jwtConf.RefreshTokenExpireTime,
})
// i18n配置
i18n.SetLang(config.Conf.Server.Lang)
// server配置
serverConfig := config.Conf.Server
gin.SetMode(serverConfig.Model)
var router = gin.New()
router.MaxMultipartMemory = 8 << 20
// 初始化接口路由
initialize.InitRouter(router, initialize.RouterConfig{ContextPath: serverConfig.ContextPath})
// 设置静态资源
setStatic(serverConfig.ContextPath, router)
// 是否允许跨域
if serverConfig.Cors {
router.Use(middleware.Cors())
}
srv := http.Server{
Addr: config.Conf.Server.GetPort(),
// 注册路由
Handler: router,
}
go func() {
<-ctx.Done()
logx.Info("Shutdown HTTP Server ...")
timeout, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := srv.Shutdown(timeout)
if err != nil {
logx.Errorf("failed to Shutdown HTTP Server: %v", err)
}
initialize.Terminate()
}()
confSrv := config.Conf.Server
logx.Infof("Listening and serving HTTP on %s", srv.Addr+confSrv.ContextPath)
var err error
if confSrv.Tls != nil && confSrv.Tls.Enable {
err = srv.ListenAndServeTLS(confSrv.Tls.CertFile, confSrv.Tls.KeyFile)
} else {
err = srv.ListenAndServe()
}
if errors.Is(err, http.ErrServerClosed) {
logx.Info("HTTP Server Shutdown")
} else if err != nil {
logx.Errorf("Failed to Start HTTP Server: %v", err)
}
}
func setStatic(contextPath string, router *gin.Engine) {
// 使用embed打包静态资源至二进制文件中
fsys, _ := fs.Sub(static.Static, "static")
fileServer := http.FileServer(http.FS(fsys))
handler := WrapStaticHandler(http.StripPrefix(contextPath, fileServer))
router.GET(contextPath+"/", handler)
router.GET(contextPath+"/favicon.ico", handler)
router.GET(contextPath+"/config.js", handler)
// 所有/assets/**开头的都是静态资源文件
router.GET(contextPath+"/assets/*file", handler)
// 设置静态资源
if staticConfs := config.Conf.Server.Static; staticConfs != nil {
for _, scs := range *staticConfs {
router.StaticFS(scs.RelativePath, http.Dir(scs.Root))
}
}
// 设置静态文件
if staticFileConfs := config.Conf.Server.StaticFile; staticFileConfs != nil {
for _, sfs := range *staticFileConfs {
router.StaticFile(sfs.RelativePath, sfs.Filepath)
}
}
}
func WrapStaticHandler(h http.Handler) gin.HandlerFunc {
return func(c *gin.Context) {
c.Writer.Header().Set("Cache-Control", `public, max-age=31536000`)
h.ServeHTTP(c.Writer, c.Request)
}
}

View File

@@ -1,7 +1,7 @@
package utils
import (
"mayfly-go/pkg/config"
"mayfly-go/internal/pkg/config"
"regexp"
)

View File

@@ -2,8 +2,8 @@ package api
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/common/utils"
"mayfly-go/internal/pkg/consts"
"mayfly-go/internal/pkg/utils"
"mayfly-go/internal/redis/api/form"
"mayfly-go/internal/redis/api/vo"
"mayfly-go/internal/redis/application"

View File

@@ -2,10 +2,10 @@ package application
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/common/utils"
flowapp "mayfly-go/internal/flow/application"
flowentity "mayfly-go/internal/flow/domain/entity"
"mayfly-go/internal/pkg/consts"
"mayfly-go/internal/pkg/utils"
"mayfly-go/internal/redis/application/dto"
"mayfly-go/internal/redis/domain/entity"
"mayfly-go/internal/redis/domain/repository"

View File

@@ -2,7 +2,7 @@ package application
import (
"fmt"
"mayfly-go/internal/common/utils"
"mayfly-go/internal/pkg/utils"
"strings"
"testing"
)

View File

@@ -1,7 +1,7 @@
package entity
import (
"mayfly-go/internal/common/utils"
"mayfly-go/internal/pkg/utils"
"mayfly-go/internal/redis/rdm"
tagentity "mayfly-go/internal/tag/domain/entity"
"mayfly-go/pkg/logx"

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -2,8 +2,8 @@ package rdm
import (
"fmt"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/machine/mcm"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/cache"
"mayfly-go/pkg/logx"
"sync"

View File

@@ -1,7 +1,7 @@
package api
import (
"mayfly-go/internal/common/utils"
"mayfly-go/internal/pkg/utils"
"mayfly-go/internal/sys/api/form"
"mayfly-go/internal/sys/api/vo"
"mayfly-go/internal/sys/application"

View File

@@ -1,12 +1,12 @@
package api
import (
"mayfly-go/internal/pkg/config"
"mayfly-go/internal/sys/api/form"
"mayfly-go/internal/sys/application"
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/imsg"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/config"
"mayfly-go/pkg/req"
"mayfly-go/pkg/utils/collx"
)

View File

@@ -2,7 +2,7 @@ package application
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/internal/sys/application/dto"
"mayfly-go/internal/sys/domain/entity"
"mayfly-go/internal/sys/domain/repository"

View File

@@ -2,7 +2,7 @@ package entity
import (
"errors"
"mayfly-go/internal/common/utils"
"mayfly-go/internal/pkg/utils"
"mayfly-go/pkg/enumx"
"mayfly-go/pkg/model"
"time"

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -3,7 +3,7 @@ package application
import (
"context"
"fmt"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/internal/tag/application/dto"
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/internal/tag/domain/repository"

View File

@@ -2,7 +2,7 @@ package application
import (
"context"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/internal/tag/domain/entity"
"mayfly-go/internal/tag/domain/repository"
"mayfly-go/internal/tag/imsg"

View File

@@ -2,7 +2,7 @@ package entity
import (
"errors"
"mayfly-go/internal/common/utils"
"mayfly-go/internal/pkg/utils"
"mayfly-go/pkg/model"
)

View File

@@ -2,7 +2,7 @@ package entity
import (
"fmt"
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/model"
"mayfly-go/pkg/utils/collx"
"strings"

View File

@@ -1,7 +1,7 @@
package imsg
import (
"mayfly-go/internal/common/consts"
"mayfly-go/internal/pkg/consts"
"mayfly-go/pkg/i18n"
)

View File

@@ -9,10 +9,10 @@ import (
_ "mayfly-go/internal/machine/init"
_ "mayfly-go/internal/mongo/init"
_ "mayfly-go/internal/msg/init"
"mayfly-go/internal/pkg/starter"
_ "mayfly-go/internal/redis/init"
_ "mayfly-go/internal/sys/init"
_ "mayfly-go/internal/tag/init"
"mayfly-go/pkg/starter"
)
func main() {

View File

@@ -17,6 +17,7 @@ import (
const (
InjectTag = "inject"
InjectMethodPrefix = "Inject"
ByTypeComponentName = "T" // 根据类型注入的组件名
)
@@ -74,14 +75,13 @@ func (c *Container) Inject(obj any) error {
// 对所有组件实例执行Inject。即为实例字段注入依赖的组件实例
func (c *Container) InjectComponents() error {
componentsGroups := collx.ArraySplit[*Component](collx.MapValues(c.components), 5)
componentsGroups := collx.ArraySplit[*Component](collx.MapValues(c.components), 10)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errGroup, _ := errgroup.WithContext(ctx)
for _, components := range componentsGroups {
components := components // 创建局部变量以在闭包中使用
errGroup.Go(func() error {
for _, v := range components {
if err := c.Inject(v.Value); err != nil {
@@ -165,7 +165,7 @@ func (c *Container) GetComponentsByType(fieldType reflect.Type) []*Component {
return components
}
// injectWithField 根据实例字段的inject:"xxx"或injectByType:""标签进行依赖注入
// injectWithField 根据实例字段的inject:"xxx"标签进行依赖注入
func (c *Container) injectWithField(context context.Context, objValue reflect.Value) error {
objValue = structx.Indirect(objValue)
objType := objValue.Type()
@@ -224,7 +224,7 @@ func (c *Container) injectByName(context context.Context, structType reflect.Typ
return fmt.Errorf("%s error: injection types are inconsistent(Expected type -> %s.%s, Component type -> %s.%s)", injectInfo, field.Type.PkgPath(), field.Type.Name(), indirectComponentType.PkgPath(), indirectComponentType.Name())
}
logx.DebugfContext(context, fmt.Sprintf("ioc field inject by name => [%s (%s) -> %s.%s#%s]", componentName, getComponentValueDesc(componentType), structType.PkgPath(), structType.Name(), field.Name))
logx.DebugfContext(context, "ioc field inject by name => [%s (%s) -> %s.%s#%s]", componentName, getComponentValueDesc(componentType), structType.PkgPath(), structType.Name(), field.Name)
if err := setFieldValue(fieldValue, component.Value); err != nil {
return fmt.Errorf("%s error: %s", injectInfo, err.Error())
@@ -244,7 +244,7 @@ func (c *Container) injectByType(context context.Context, structType reflect.Typ
return fmt.Errorf("%s error: %s", injectInfo, err.Error())
}
logx.DebugfContext(context, fmt.Sprintf("ioc field inject by type => [%s.%s (%s) -> %s.%s#%s]", fieldType.PkgPath(), fieldType.Name(), getComponentValueDesc(component.GetType()), structType.PkgPath(), structType.Name(), field.Name))
logx.DebugfContext(context, "ioc field inject by type => [%s.%s (%s) -> %s.%s#%s]", fieldType.PkgPath(), fieldType.Name(), getComponentValueDesc(component.GetType()), structType.PkgPath(), structType.Name(), field.Name)
if err := setFieldValue(fieldValue, component.Value); err != nil {
return fmt.Errorf("%s error: %s", injectInfo, err.Error())
@@ -261,8 +261,8 @@ func (c *Container) injectWithMethod(context context.Context, objValue reflect.V
method := objType.Method(i)
methodName := method.Name
// 不是以Inject开头的函数,则默认跳过
if !strings.HasPrefix(methodName, "Inject") {
// 不是以指定方法名前缀开头的函数,则默认跳过
if !strings.HasPrefix(methodName, InjectMethodPrefix) {
continue
}

View File

@@ -4,7 +4,6 @@ import (
"encoding/json"
"fmt"
"mayfly-go/pkg/cache"
"mayfly-go/pkg/config"
"mayfly-go/pkg/contextx"
"mayfly-go/pkg/errorx"
"mayfly-go/pkg/model"
@@ -107,7 +106,7 @@ type DefaultPermissionCodeRegistry struct {
func (r *DefaultPermissionCodeRegistry) SaveCodes(userId uint64, codes []string) {
if r.cache == nil {
r.cache = cache.NewTimedCache(time.Minute*time.Duration(config.Conf.Jwt.ExpireTime), 5*time.Second)
r.cache = cache.NewTimedCache(time.Minute*time.Duration(jwtConf.ExpireTime), 5*time.Second)
}
r.cache.Put(fmt.Sprintf("%v", userId), codes)
}
@@ -138,7 +137,7 @@ type RedisPermissionCodeRegistry struct {
}
func (r *RedisPermissionCodeRegistry) SaveCodes(userId uint64, codes []string) {
rediscli.Set(fmt.Sprintf("mayfly:%v:codes", userId), anyx.ToString(codes), time.Minute*time.Duration(config.Conf.Jwt.ExpireTime))
rediscli.Set(fmt.Sprintf("mayfly:%v:codes", userId), anyx.ToString(codes), time.Minute*time.Duration(jwtConf.ExpireTime))
}
func (r *RedisPermissionCodeRegistry) HasCode(userId uint64, code string) bool {

View File

@@ -2,15 +2,33 @@ package req
import (
"errors"
"mayfly-go/pkg/config"
"mayfly-go/pkg/utils/stringx"
"time"
"github.com/golang-jwt/jwt/v5"
)
// JwtConf jwt配置
type JwtConf struct {
Key string
ExpireTime uint64 // 过期时间,单位分钟
RefreshTokenExpireTime uint64 // 刷新token的过期时间单位分钟
}
// 默认jwt配置
var jwtConf = JwtConf{
Key: stringx.RandUUID(),
ExpireTime: 60,
RefreshTokenExpireTime: 360,
}
// SetJwtConf 设置jwt配置
func SetJwtConf(conf JwtConf) {
jwtConf = conf
}
// 创建用户token
func CreateToken(userId uint64, username string) (accessToken string, refreshToken string, err error) {
jwtConf := config.Conf.Jwt
now := time.Now()
// 带权限创建令牌
@@ -46,7 +64,7 @@ func ParseToken(tokenStr string) (uint64, string, error) {
// Parse token
token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (any, error) {
return []byte(config.Conf.Jwt.Key), nil
return []byte(jwtConf.Key), nil
})
if err != nil || token == nil {
return 0, "", err

View File

@@ -1,66 +0,0 @@
package starter
import (
"context"
"errors"
"mayfly-go/initialize"
"mayfly-go/pkg/config"
"mayfly-go/pkg/i18n"
"mayfly-go/pkg/logx"
"mayfly-go/pkg/req"
"net/http"
"time"
sysapp "mayfly-go/internal/sys/application"
"github.com/gin-gonic/gin"
)
func runWebServer(ctx context.Context) {
// 设置gin日志输出器
logOut := logx.GetConfig().GetLogOut()
gin.DefaultErrorWriter = logOut
gin.DefaultWriter = logOut
// 权限处理器
req.UseBeforeHandlerInterceptor(req.PermissionHandler)
// 日志处理器
req.UseAfterHandlerInterceptor(req.LogHandler)
// 设置日志保存函数
req.SetSaveLogFunc(sysapp.GetSyslogApp().SaveFromReq)
i18n.SetLang(config.Conf.Server.Lang)
srv := http.Server{
Addr: config.Conf.Server.GetPort(),
// 注册路由
Handler: initialize.InitRouter(),
}
go func() {
<-ctx.Done()
logx.Info("Shutdown HTTP Server ...")
timeout, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := srv.Shutdown(timeout)
if err != nil {
logx.Errorf("failed to Shutdown HTTP Server: %v", err)
}
initialize.Terminate()
}()
confSrv := config.Conf.Server
logx.Infof("Listening and serving HTTP on %s", srv.Addr+confSrv.ContextPath)
var err error
if confSrv.Tls != nil && confSrv.Tls.Enable {
err = srv.ListenAndServeTLS(confSrv.Tls.CertFile, confSrv.Tls.KeyFile)
} else {
err = srv.ListenAndServe()
}
if errors.Is(err, http.ErrServerClosed) {
logx.Info("HTTP Server Shutdown")
} else if err != nil {
logx.Errorf("Failed to Start HTTP Server: %v", err)
}
}

View File

@@ -14,13 +14,6 @@ var (
patternErrMsg map[string]string
)
// 注册自定义正则表达式校验规则
func RegisterCustomPatterns() {
// 账号用户名校验
RegisterPattern("account_username", "^[a-zA-Z0-9_]{5,20}$", "只允许输入5-20位大小写字母、数字、下划线")
RegisterPattern("resource_code", "^[a-zA-Z0-9_\\-.:]{1,32}$", "只允许输入1-32位大小写字母、数字、_-.:")
}
// 注册自定义正则表达式
func RegisterPattern(patternName string, regexpStr string, errMsg string) {
if regexpMap == nil {

View File

@@ -50,9 +50,6 @@ func Init() {
// 注册自定义校验器
validate.RegisterValidation(CustomPatternTagName, patternValidFunc)
// 注册自定义正则校验规则
RegisterCustomPatterns()
}
// Translate 翻译错误信息