RuleGo RuleGo
🏠首页
  • 快速入门
  • 规则链
  • 标准组件
  • 扩展组件
  • 自定义组件
  • 可视化
  • RuleGo-Server
  • AOP
  • 触发器
  • 高级主题
  • 性能
  • 标准组件
  • 扩展组件
  • 自定义组件
  • 流式计算
  • 组件市场
  • 概述
  • 快速入门
  • 路由
  • DSL
  • API
  • Options
  • 组件
🔥编辑器 (opens new window)
  • 可视化编辑器 (opens new window)
  • RuleGo-Server (opens new window)
  • 🌊StreamSQL
  • 🤖智能体框架
  • 🦀TPCLAW 智能体平台 (opens new window)
  • ❓问答

    • FAQ
💖支持
👥加入社区
  • Github (opens new window)
  • Gitee (opens new window)
  • GitCode (opens new window)
  • 更新日志 (opens new window)
  • English
  • 简体中文
🏠首页
  • 快速入门
  • 规则链
  • 标准组件
  • 扩展组件
  • 自定义组件
  • 可视化
  • RuleGo-Server
  • AOP
  • 触发器
  • 高级主题
  • 性能
  • 标准组件
  • 扩展组件
  • 自定义组件
  • 流式计算
  • 组件市场
  • 概述
  • 快速入门
  • 路由
  • DSL
  • API
  • Options
  • 组件
🔥编辑器 (opens new window)
  • 可视化编辑器 (opens new window)
  • RuleGo-Server (opens new window)
  • 🌊StreamSQL
  • 🤖智能体框架
  • 🦀TPCLAW 智能体平台 (opens new window)
  • ❓问答

    • FAQ
💖支持
👥加入社区
  • Github (opens new window)
  • Gitee (opens new window)
  • GitCode (opens new window)
  • 更新日志 (opens new window)
  • English
  • 简体中文

广告采用随机轮播方式显示 ❤️成为赞助商
  • 快速入门

  • 规则链

  • 标准组件

  • 扩展组件

  • 自定义组件

  • 组件市场

  • 可视化

  • AOP

  • 触发器

  • 高级主题

  • 智能体框架

  • RuleGo-Server

    • 概述与快速开始
    • 安装与部署
    • 用户认证与权限
    • REST API 参考
    • MCP 服务
    • AI 功能
    • 组件市场
    • 运行日志
    • 国际化
    • 二次开发
      • 项目结构
      • 两种使用方式
        • 方式一:独立运行
        • 方式二:嵌入现有应用
        • Gin 示例
        • 快捷方式
        • 手动控制生命周期
      • 模块系统
        • 自定义模块
      • 服务容器(DI)
        • 核心服务键
      • 自定义认证器
      • 自定义授权器
      • 自定义存储
      • 生命周期钩子
      • 应用选项
      • 热重载
      • 构建标签
      • 多租户
    • 规则链部署与调用
    • 可视化编辑器

  • 问题

目录

二次开发

RuleGo-Server 采用模块化架构,可以独立运行,也可以作为中间件嵌入到现有应用(如 Gin、Echo)中。提供服务容器(DI)、可替换存储、生命周期钩子等扩展能力。

# 项目结构

server/
├── cmd/server/          # 入口 + 构建标签注册
├── app/                 # 公共:App 生命周期、Container、Module 接口
├── config/              # 公共:配置结构与加载器
├── services/            # 公共:服务接口定义
├── model/               # 公共:数据模型
├── store/               # 公共:存储接口
├── bridge/              # 公共:HTTP 桥接(嵌入其他框架)
├── bootstrap/           # 公共:默认模块组装
├── internal/
│   ├── endpoint/        # REST + WebSocket 路由
│   ├── modules/         # 业务模块实现
│   │   ├── rule/        #   规则链模块
│   │   ├── user/        #   用户认证模块
│   │   ├── node/        #   节点池模块
│   │   ├── runlog/      #   执行日志模块
│   │   ├── locale/      #   国际化模块
│   │   ├── skill/       #   技能模块
│   │   ├── system/      #   系统配置模块
│   │   ├── marketplace/ #   市场模块
│   │   └── mcp/         #   MCP 模块
│   ├── store/           # 存储实现
│   │   ├── filestore/   #   文件存储(默认)
│   │   ├── bboltstore/  #   BBolt 存储
│   │   ├── jsonlstore/  #   JSONL 存储
│   │   └── nopstore/    #   空存储
│   └── registry/        # 内置组件注册
├── data/                # 运行时数据
└── editor/              # 前端静态资源
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

# 两种使用方式

# 方式一:独立运行

RuleGo-Server 作为独立中间件运行,是最简单的使用方式:

package main

import (
    "github.com/rulego/rulego/server/bootstrap"
    // 按需导入组件
    _ "github.com/rulego/rulego-components-ai/all"
)

func main() {
    application := bootstrap.DefaultApp("./config.conf")
    bootstrap.Run(application)
}
1
2
3
4
5
6
7
8
9
10
11
12

bootstrap.DefaultApp 等价于:

app.New(
    app.WithConfigFile("./config.conf"),
    app.WithModules(bootstrap.DefaultModules()...),
)
1
2
3
4

# 方式二:嵌入现有应用

通过 bridge.Bridge 将完整的 RuleGo REST API 桥接到宿主框架,无需手动注册路由。

# Gin 示例

package main

import (
    "github.com/gin-gonic/gin"
    "github.com/rulego/rulego/server/app"
    "github.com/rulego/rulego/server/bootstrap"
    "github.com/rulego/rulego/server/bridge"
)

func main() {
    application := bootstrap.DefaultApp("./config.conf")
    b, err := bridge.NewBridge(application)
    if err != nil {
        panic(err)
    }
    defer b.Stop()

    r := gin.Default()

    // 用户自己的路由(优先匹配)
    r.GET("/api/users", userListHandler)

    // RuleGo 完整 API,未匹配的路由全部交给 Bridge 处理
    r.Any("/*path", gin.WrapH(b.Handler()))

    _ = r.Run(":8080")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

# 快捷方式

如果不需要自定义路由,可以使用更简洁的 NewBridgeWithDefaults:

b, _ := bridge.NewBridgeWithDefaults("./config.conf")
defer b.Stop()
handler := b.Handler() // 标准 http.Handler,可接入任何 http 框架
1
2
3

# 手动控制生命周期

嵌入模式下可以精细控制 App 的初始化和启动:

application := app.New(
    app.WithConfigFile("./config.conf"),
    app.WithModules(bootstrap.DefaultModules()...),
)

// 初始化(加载配置、注册模块)
if err := application.Init(); err != nil {
    panic(err)
}

// 启动
if err := application.Start(); err != nil {
    panic(err)
}

// 停止
defer application.Stop()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 模块系统

所有功能以 Module 接口实现,拥有 Init → Start → Stop 生命周期:

type Module interface {
    Name() string
    Priority() int  // 数字越小越先初始化
    Init(ctx *ModuleContext) error
    Start(ctx context.Context) error
    Stop(ctx context.Context) error
}

type ModuleContext struct {
    Container *Container
    Config    *config.Config
    Logger    types.Logger
    DataDir   string
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

内置模块:

模块 优先级 说明
user 10 认证与授权
mcp 25 MCP 服务
rule 30 规则链管理
node 35 节点池管理
runlog 45 运行日志
locale 50 国际化
skill 55 技能管理
system 65 系统配置
marketplace 70 组件市场
debug 75 调试服务

# 自定义模块

实现 Module 接口,通过 WithModules() 注入:

type MyModule struct{}

func (m *MyModule) Name() string     { return "my_module" }
func (m *MyModule) Priority() int    { return 50 }
func (m *MyModule) Init(ctx *app.ModuleContext) error {
    // 注册服务到容器
    ctx.Container.Register("module.my_module.service", &MyService{})
    return nil
}
func (m *MyModule) Start(ctx context.Context) error { return nil }
func (m *MyModule) Stop(ctx context.Context) error  { return nil }

// 使用
application := app.New(
    app.WithConfigFile("./config.conf"),
    app.WithModules(append(bootstrap.DefaultModules(), &MyModule{})...),
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

用 WithModuleOverride() 替换内置模块(如替换默认的 rule 模块):

application := app.New(
    app.WithConfigFile("./config.conf"),
    app.WithModules(bootstrap.DefaultModules()...),
    app.WithModuleOverride(&MyRuleModule{}),  // 替换 Name() == "rule" 的模块
)
1
2
3
4
5

# 服务容器(DI)

轻量级依赖注入容器,模块通过名称注册和获取服务:

// 注册服务(不允许覆盖同名服务)
container.Register("module.rule.executor", executor)

// 替换已有服务(强制覆盖)
container.Replace(services.KeyAuthenticator, &OAuth2Authenticator{})

// 获取服务
executor, err := app.GetAs[services.ChainExecutor](container, services.KeyRuleExecutor)

// 获取服务(失败 panic)
executor := app.MustGetAs[services.ChainExecutor](container, services.KeyRuleExecutor)
1
2
3
4
5
6
7
8
9
10
11

# 核心服务键

常量 值 接口 说明
KeyRuleCatalog module.rule.catalog ChainCatalog 规则链目录(只读)
KeyRuleExecutor module.rule.executor ChainExecutor 执行规则链
KeyRuleManager module.rule.manager RuleAdminService 规则链管理(增删改部署)
KeyEngineManager module.rule.engine_manager EngineManager 多租户引擎池
KeyNodeService module.node.service NodeService 组件 + 节点池操作
KeyRunLogService module.runlog.service RunLogService 运行日志
KeyLocaleService module.locale.service LocaleService 国际化
KeyMarketplaceService module.marketplace.service MarketplaceService 市场
KeyMcpService module.mcp.service McpService MCP 协议服务
KeyConfigService module.system.settings ConfigService 系统配置
KeyAuthService module.user.auth AuthService 密码/API Key 认证
KeyUserProfile module.user.profile UserReader 用户信息读取
KeyAuthenticator module.user.authenticator Authenticator 身份认证(可替换)
KeyAuthorizer module.user.authorizer Authorizer 权限校验(可替换)
KeySkillService module.skill.service SkillService AI 技能管理
KeyDebugService module.debug.service DebugService 调试服务

# 自定义认证器

替换默认认证器实现 OAuth2、LDAP 等:

type Authenticator interface {
    Authenticate(r *http.Request) (*model.UserContext, error)
}
1
2
3

在模块 Init 中通过容器替换:

func (m *MyModule) Init(ctx *app.ModuleContext) error {
    ctx.Container.Replace(services.KeyAuthenticator, &OAuth2Authenticator{})
    return nil
}
1
2
3
4

# 自定义授权器

实现 RBAC、ABAC 等权限控制:

type Authorizer interface {
    Authorize(user *model.UserContext, resource, action string) bool
}
1
2
3

同样在模块 Init 中替换:

func (m *MyModule) Init(ctx *app.ModuleContext) error {
    ctx.Container.Replace(services.KeyAuthorizer, &RBACAuthorizer{})
    return nil
}
1
2
3
4

# 自定义存储

实现 StoreProvider 接口,通过 WithStoreProvider() 注入数据库存储:

type StoreProvider interface {
    GetRuleStore(username string) (RuleStore, error)
    GetSettingStore(username string) (SettingStore, error)
    GetComponentStore(username string) (ComponentStore, error)
    GetNodePoolStore(username string) (NodePoolStore, error)
    GetUserStore() (UserStore, error)
    GetRunLogStore() (RunLogStore, error)
}
1
2
3
4
5
6
7
8
application := app.New(
    app.WithConfigFile("./config.conf"),
    app.WithStoreProvider(&MyDbStoreProvider{db: myDb}),
    app.WithModules(bootstrap.DefaultModules()...),
)
1
2
3
4
5

默认使用文件存储(filestore),可替换为 MySQL、PostgreSQL 等。

# 生命周期钩子

通过 WithHooks() 在 App 生命周期的 5 个阶段插入逻辑:

application := app.New(
    app.WithConfigFile("./config.conf"),
    app.WithModules(bootstrap.DefaultModules()...),
    app.WithHooks(
        app.NewFuncHook("my_hook", app.AfterStart, 0,
            func(ctx context.Context, appCtx *app.ModuleContext) error {
                // 应用启动后的初始化逻辑
                return nil
            },
        ),
    ),
)
1
2
3
4
5
6
7
8
9
10
11
12

阶段顺序:BeforeInit → AfterInit → BeforeStart → AfterStart → OnStop

# 应用选项

app.New() 支持以下函数选项:

Option 说明
WithConfigFile(path) 配置文件路径
WithModules(m...) 添加模块
WithModuleOverride(m) 按名称替换已注册的模块
WithStoreProvider(p) 注入自定义存储提供者(替换默认文件存储)
WithHooks(h...) 添加生命周期钩子
WithGlobal(props) 注入全局配置,与配置文件 [global] 合并(注入值覆盖文件值)
WithTypesLogger(l) 注入自定义日志器(Zap、Logrus 等)
WithTransportDisabled() 禁用默认传输层(嵌入式模式)
WithoutAutoMkdir() 禁用 Init 时自动创建数据目录

# 热重载

支持运行时重新加载配置,无需重启进程:

application.Reload() // 停止所有模块 → 重载配置 → 重新初始化 → 启动
1

# 构建标签

通过 Go build tags 按需引入组件:

// cmd/server/with_ai.go
//go:build with_ai

import _ "github.com/rulego/rulego-components-ai/all"
1
2
3
4
# 标准构建
go build -o server ./cmd/server/

# 带 AI 组件
go build -tags "with_ai" -o server ./cmd/server/

# 带所有可选组件
go build -tags "with_all" -o server ./cmd/server/

# 或逐个指定
go build -tags "with_ai,with_iot,with_etl,with_ci,with_extend" -o server ./cmd/server/
1
2
3
4
5
6
7
8
9
10
11
标签 说明
with_all 所有可选组件(等同于同时启用下面全部标签)
with_ai AI 组件(ai/agent、LLM 工具)
with_iot IoT 组件(OPC UA、Modbus、Serial)
with_etl ETL 数据处理组件(MySQL CDC)
with_ci CI/CD 组件
with_extend 扩展组件(Kafka、NATS、Redis、RabbitMQ、MongoDB、gRPC 等)

# 多租户

EngineManager 为每个用户维护独立的规则引擎池:

  • 规则链按用户隔离
  • 组件配置按用户隔离
  • 共享节点按用户隔离
  • 系统配置按用户隔离

用户身份通过 ContextWithMCPRequestingUser 注入到执行上下文。

在 GitHub 上编辑此页 (opens new window)
上次更新: 2026/06/02, 01:16:21
国际化
规则链部署与调用

← 国际化 规则链部署与调用→

Theme by Vdoing | Copyright © 2023-2026 RuleGo Team | Apache 2.0 License

  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式