任务三

This commit is contained in:
Yvan
2026-01-07 19:10:02 +08:00
parent 3c0f3b7165
commit be3b6641a6
50 changed files with 2916 additions and 1167 deletions
+73 -8
View File
@@ -1,28 +1,93 @@
package server
import (
"context"
"kra/internal/conf"
"kra/internal/server/middleware"
"kra/internal/service/system"
"kra/pkg/jwt"
"kra/pkg/response"
"github.com/go-kratos/kratos/v2/middleware/recovery"
"github.com/go-kratos/kratos/v2/transport/http"
"github.com/go-kratos/kratos/v2/middleware/selector"
khttp "github.com/go-kratos/kratos/v2/transport/http"
)
// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server) *http.Server {
var opts = []http.ServerOption{
http.Middleware(
func NewHTTPServer(
c *conf.Server,
jwtPkg *jwt.JWT,
userSvc *system.UserService,
apiSvc *system.ApiService,
authoritySvc *system.AuthorityService,
authorityBtnSvc *system.AuthorityBtnService,
captchaSvc *system.CaptchaService,
casbinSvc *system.CasbinService,
menuSvc *system.MenuService,
dictionarySvc *system.DictionaryService,
jwtBlacklistSvc *system.JwtBlacklistService,
operationRecordSvc *system.OperationRecordService,
paramsSvc *system.ParamsService,
systemConfigSvc *system.SystemConfigService,
) *khttp.Server {
var opts = []khttp.ServerOption{
khttp.Middleware(
recovery.Recovery(),
// JWT认证中间件(排除公开路由)
selector.Server(
middleware.JWTAuthSimple(jwtPkg),
).Match(newWhiteListMatcher()).Build(),
),
khttp.ResponseEncoder(response.Encoder),
khttp.ErrorEncoder(response.ErrorEncoder),
}
if c.Http.Network != "" {
opts = append(opts, http.Network(c.Http.Network))
opts = append(opts, khttp.Network(c.Http.Network))
}
if c.Http.Addr != "" {
opts = append(opts, http.Address(c.Http.Addr))
opts = append(opts, khttp.Address(c.Http.Addr))
}
if c.Http.Timeout != nil {
opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
opts = append(opts, khttp.Timeout(c.Http.Timeout.AsDuration()))
}
srv := http.NewServer(opts...)
srv := khttp.NewServer(opts...)
// 创建路由组
rg := &system.RouterGroup{
Public: srv.Route("/"),
Private: srv.Route("/"),
PrivateWithRecord: srv.Route("/"),
}
// 注册各模块路由
userSvc.RegisterRoutes(rg)
apiSvc.RegisterRoutes(rg)
authoritySvc.RegisterRoutes(rg)
authorityBtnSvc.RegisterRoutes(rg)
captchaSvc.RegisterRoutes(rg)
casbinSvc.RegisterRoutes(rg)
menuSvc.RegisterRoutes(rg)
dictionarySvc.RegisterRoutes(rg)
jwtBlacklistSvc.RegisterRoutes(rg)
operationRecordSvc.RegisterRoutes(rg)
paramsSvc.RegisterRoutes(rg)
systemConfigSvc.RegisterRoutes(rg)
return srv
}
// newWhiteListMatcher 创建白名单匹配器(这些路由不需要JWT认证)
func newWhiteListMatcher() selector.MatchFunc {
whiteList := map[string]struct{}{
"/base/login": {},
"/base/captcha": {},
"/api/freshCasbin": {},
}
return func(ctx context.Context, operation string) bool {
if _, ok := whiteList[operation]; ok {
return false // 不需要认证
}
return true // 需要认证
}
}