package server import ( "context" pb "rag/file-system/api/file/v1" "rag/file-system/internal/conf" "rag/file-system/internal/service" jwtv5 "github.com/golang-jwt/jwt/v5" "github.com/go-kratos/kratos/v2/log" "github.com/go-kratos/kratos/v2/middleware/auth/jwt" "github.com/go-kratos/kratos/v2/middleware/logging" "github.com/go-kratos/kratos/v2/middleware/recovery" "github.com/go-kratos/kratos/v2/middleware/selector" "github.com/go-kratos/kratos/v2/middleware/tracing" kgrpc "github.com/go-kratos/kratos/v2/transport/grpc" ) func NewGRPCServer(c *conf.Server, auth *conf.Auth, svc *service.FileService, logger log.Logger) *kgrpc.Server { jwtMiddleware := jwt.Server( func(token *jwtv5.Token) (interface{}, error) { return []byte(auth.GetJwtKey()), nil }, ) // Selector: apply JWT to all routes EXCEPT public share endpoints authSelector := selector.Server(jwtMiddleware).Match(func(ctx context.Context, operation string) bool { switch operation { case "/api.file.v1.FileService/GetShareInfo", "/api.file.v1.FileService/DownloadShare": return false // skip JWT for public share access default: return true // apply JWT to all other endpoints } }).Build() opts := []kgrpc.ServerOption{ kgrpc.Middleware( recovery.Recovery(), tracing.Server(), logging.Server(logger), authSelector, ), } if c != nil && c.Grpc != nil { if c.Grpc.Addr != "" { opts = append(opts, kgrpc.Address(c.Grpc.Addr)) } if c.Grpc.Timeout != nil { opts = append(opts, kgrpc.Timeout(c.Grpc.Timeout.AsDuration())) } } srv := kgrpc.NewServer(opts...) pb.RegisterFileServiceServer(srv, svc) return srv }