94 lines
2.5 KiB
Go
94 lines
2.5 KiB
Go
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/middleware/selector"
|
||
khttp "github.com/go-kratos/kratos/v2/transport/http"
|
||
)
|
||
|
||
// NewHTTPServer new an HTTP server.
|
||
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, khttp.Network(c.Http.Network))
|
||
}
|
||
if c.Http.Addr != "" {
|
||
opts = append(opts, khttp.Address(c.Http.Addr))
|
||
}
|
||
if c.Http.Timeout != nil {
|
||
opts = append(opts, khttp.Timeout(c.Http.Timeout.AsDuration()))
|
||
}
|
||
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 // 需要认证
|
||
}
|
||
}
|