harbor

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 34 Imported by: 0

README

harbor Framework

Version

Harbor 1.1.0:面向模块化单体、可平滑演进到多服务的 Go 应用框架。
核心只做装配、生命周期与稳定契约;数据库、路由、缓存、消息等按需接入。业务登录与领域逻辑留在你的 SubApp,不进框架仓库。

为什么用 Harbor

很多 Go 项目会从「手写 main + 全局变量 + 一堆 init」长成难拆的单体:依赖缠在一起、启动失败不好回滚、Web 与定时/命令行各写一套、加 Redis/支付又把主库依赖撑爆。

Harbor 把这些横切问题收成可复用约定,让你把时间花在业务上:

你要解决的问题 Harbor 怎么帮你
多业务模块挤在一个进程里,边界模糊 SubApp:按子系统拆目录与装配,同一进程可挂多个 SubApp
依赖手工 new,测试/替换成本高 dig 构造函数注入 + 启动期 Bind 校验与诊断
启动半截挂掉、退出泄漏连接 生命周期状态机:Register → Boot → Run → 逆序 Shutdown,失败可回滚
Web 和 CLI 两套脚手架 同一 ApplicationWebShell / ConsoleShell
框架又大又重,没用到的 SDK 也进依赖 L0/L1/L2 分层 + 边缘能力独立 x/* module,按需 go get
上线缺探针、限流、维护窗口 可运营默认能力:健康检查、治理中间件、维护模式、可选 Metrics/OTel
每个项目重复造配置/日志/校验 L1 核心组件默装;扩展 Provider 显式注册,行为可预期

适合:中后台、运营系统、模块化单体(先一个仓多个 SubApp,以后再拆服务)。
不适合:只要一个 50 行 HTTP demo、或要把整套业务 CRUD/RBAC 塞进框架里——Harbor 刻意不做「业务超市」。

使用框架的好处

  1. 启动与退出可控
    明确阶段与错误包装(含 Provider / 构造函数名);启动失败回滚已 Boot 资源;进程退出 LIFO 关闭连接池、订阅等。

  2. 模块可组合、依赖可选
    SubApp 自己声明 Binds()ServiceProviders();不用的 DB / Auth / 支付不会进你的二进制依赖图。

  3. 契约稳定、实现可换
    contract/* 定义日志、配置、错误、鉴权、缓存等接口;业务依赖接口,Provider 可替换而不改业务签名。

  4. Web 与运维开箱
    统一响应形状、AccessLevel 守卫、/livez /readyz、超时/限流/熔断、维护模式 503;需要时再开 Prometheus / OpenTelemetry / OpenAPI。

  5. 工程可复制
    CLI 脚手架生成 SubApp / Provider;文档按生命周期 → 契约 → 组件索引组织;最低 Go 1.26,公开 API 优先泛型与标准库新能力。

  6. 演进路径清晰
    今天:一个仓库多个 SubApp 的模块化单体。
    明天:把某个 SubApp 迁成独立服务时,生命周期与 Provider 边界已经分开,不必从全局变量堆里挖。

核心特性

特性 说明
SubApp 模块模型 业务按子应用组织;菜单、路由、命令、Binds、Providers 各管一亩三分地
Service Provider Register / Boot / Conf / 可选 Shutdown;默认配置落盘与键校验
DI(dig) 构造函数注入;启动期校验;ProvidersOf[T]DebugContainerHARBOR_DI_DEBUG
生命周期 显式状态机;Boot 幂等;失败回滚;信号驱动优雅关闭
统一错误与响应 contract/errors(Kind / AppError)+ router 统一 JSON;中间件治理响应一致
可运营 健康聚合、维护模式、限流/超时/熔断;可选 Metrics、OTel(含 OTLP)、OpenAPI 导出
Auth(可选) JWT TokenService / Authorizer + AccessLevel 自动守卫;不含业务登录/用户表
分层与瘦身 L0 Kernel → L1 核心组件 → L2 扩展;支付/OCR/MQ/存储等在 x/ 独立 module
现代 Go 最低 Go 1.26;BindJSON[T]BaseRepository[T, ID]errors.AsType

分层与目录地图

业务 SubApp(admin / order / …)     ← 不在本仓库
─────────────────────────────────
L2 扩展          provider/* 、x/*
L1 核心组件      provider/conf|log|validator|event|appconf
L0 核心框架      application.go 、core/ 、contract/

完整约定见 docs/architecture/core-vs-extension.md

L0 核心框架(Kernel)

应用怎么创建、装配、启动、失败回滚、优雅退出。无第三方业务 SDK。

路径 用途
application.goservice_installer.go NewApp / WebShell / ConsoleShell 入口
core/lifecycle/ 生命周期状态机、Register / Boot / Shutdown
core/di/ Dig Bind 校验与依赖诊断
core/resource/ 资源组逆序关闭辅助
core/convert/ 官方类型转换 API
contract/foundation/ ApplicationServiceProvider 等基础契约
contract/errors/ Kind / AppError / HTTP 映射
contract/log/contract/conf/contract/health/contract/cache/contract/auth/contract/pay/ 稳定接口(实现分别在 L1 / L2)
contract/context.go 通用 WithContext 契约
L1 核心组件(Core Components)

几乎每个应用都要用的横切能力;NewApp 默装或强烈推荐具备。只依赖 L0。

路径 用途
provider/conf/ 配置加载、键校验、环境覆盖、HARBOR_CONF_STRICT
provider/appconf/ 应用级配置(app.yaml
provider/log/ 日志实现(契约在 contract/log
provider/validator/ 请求 / 配置校验
provider/event/ 进程内事件总线
L2 扩展组件(Extension)

按 SubApp ServiceProviders() 显式注册。分两类:

主 module(仍在本仓库 provider/,与主 go.mod 同仓)

路径 用途
provider/router/ HTTP 路由、中间件、统一响应、OpenAPI、健康探针挂载
provider/auth/ JWT TokenService / Authorizer(不含业务登录)
provider/permission/ Casbin 权限守卫
provider/db/ GORM 数据库 + BaseRepository
provider/redis/ Redis 客户端
provider/cache/ 缓存实现(memory / redis,契约在 contract/cache
provider/otel/ OpenTelemetry(stdout / noop / OTLP)

独立 module(x/,各自 go.mod,避免主库依赖膨胀)

路径 用途
x/pay 支付适配
x/ocr OCR
x/mqttx/rabbitmqx/socketio 消息 / 实时通道
x/storage 对象存储
x/captcha 验证码
x/clickhouse ClickHouse

迁移与 import 对照见 x/README.md。本地开发用根目录 go.work 同时引用主库与扩展。

其他目录
路径 用途
runtime/health/ 健康聚合(liveness / readiness)
utils/ 通用工具(hash、雪花 ID、文件等)
lang/ 内置文案(zh / en)
testing/ 框架侧测试辅助
tooling/ CLI 脚手架(make subapp / make provider)、依赖边界检查
sub-utils/ Console 子系统示例(非业务产品)
docs/ 使用手册、组件说明、架构与路线图

环境要求

  • 最低 Go 版本:1.26(以根目录 go.modgo 行为准)
  • 框架与贡献代码应主动使用 1.26+ 能力:泛型、errors.AsTypeslices / maps、迭代器等;避免无必要的 any / 反射与手写循环

工程约定详见 docs/architecture/core-vs-extension.md 末尾「语言与 API 约定」。

安装

go get gitcode.com/harbor-labs/harbor@v1.1.0

本地开发:

git clone https://gitcode.com/harbor-labs/harbor.git
cd harbor
go mod download

本仓库是框架库,没有根目录 main.go。可参考 sub-utils/(Console 示例)与 docs/

最小启动

app, err := harbor.NewApp(&admin.SubAppAdmin{})
if err != nil {
    log.Fatal(err)
}
if err := app.WebShell(); err != nil {
    log.Fatal(err)
}

扩展组件在 SubApp 里按需挂载,例如:

func (a *SubApp) ServiceProviders() []foundation.ServiceProvider {
    return []foundation.ServiceProvider{
        &db.DBServiceProvider{},
        &router.RouterServiceProvider{},
        &auth.JwtServiceProvider{},
        // 边缘扩展:&pay.PayServiceProvider{}  // gitcode.com/harbor-labs/harbor/x/pay
    }
}

文档

文档 说明
docs/ 框架使用手册(生命周期 → SubApp → Provider → 实战)
docs/architecture/core-vs-extension.md L0 / L1 / L2 分层约定
docs/components/README.md 组件索引
x/README.md 边缘扩展 module 迁移
docs/roadmap/v1.1-improvement-plan.md v1.1 改进计划
CHANGELOG.md 版本变更

脚手架

go run ./tooling/cmd/harbor make subapp --name demo
go run ./tooling/cmd/harbor make provider --name demo

许可证

本项目基于 bit-labs-cn/owl Fork,采用 MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsValidBinaryName

func IsValidBinaryName(binName string) error

IsValidBinaryName 检查二进制文件名是否合法

func NewServiceCommandGetter

func NewServiceCommandGetter(app Installable) *cobra.Command

func ProvidersOf added in v1.1.0

func ProvidersOf[T any](app *Application) []T

ProvidersOf 按类型过滤已注册 Provider(推荐;避免 GetProviders + 断言)。

Types

type Application

type Application struct {
	*dig.Container
	// contains filtered or unexported fields
}

func NewApp

func NewApp(apps ...SubApp) (*Application, error)

NewApp 创建应用。路径或基础绑定失败时返回错误。

func (*Application) Boot

func (i *Application) Boot(ctx context.Context) error

func (*Application) Booted

func (i *Application) Booted(callback func(application foundation.Application))

func (*Application) Booting

func (i *Application) Booting(callback func(application foundation.Application))

func (*Application) ConsoleShell

func (i *Application) ConsoleShell(rootCmd *cobra.Command) error

ConsoleShell 使用命令行壳启动系统。

func (*Application) DebugContainer added in v1.1.0

func (i *Application) DebugContainer() string

DebugContainer 返回 dig 依赖图文本,便于诊断缺失依赖。

func (*Application) Environment

func (i *Application) Environment(s ...string) (string, bool)

func (*Application) GetBasePath

func (i *Application) GetBasePath() string

func (*Application) GetBootstrapPath

func (i *Application) GetBootstrapPath() string

func (*Application) GetConfigPath

func (i *Application) GetConfigPath() string

func (*Application) GetLangPath

func (i *Application) GetLangPath() string

func (*Application) GetLocale

func (i *Application) GetLocale() string

func (*Application) GetProviders

func (i *Application) GetProviders(provider interface{}) []interface{}

func (*Application) GetPublicPath

func (i *Application) GetPublicPath() string

func (*Application) GetResourcePath

func (i *Application) GetResourcePath() string

func (*Application) GetStoragePath

func (i *Application) GetStoragePath() string

func (*Application) HasBeenBootstrapped

func (i *Application) HasBeenBootstrapped() bool

func (*Application) Invoke

func (i *Application) Invoke(function interface{}, opts ...dig.InvokeOption) error

func (*Application) IsDownForMaintenance

func (i *Application) IsDownForMaintenance() bool

func (*Application) LifecycleState added in v1.1.0

func (i *Application) LifecycleState() string

func (*Application) MaintenanceMode

func (i *Application) MaintenanceMode() context.Context

func (*Application) Provide

func (i *Application) Provide(function interface{}, opts ...dig.ProvideOption) error

func (*Application) Register

func (i *Application) Register(providers ...any) error

func (*Application) SetLocale

func (i *Application) SetLocale(locale string)

func (*Application) SetMaintenanceMode added in v1.1.0

func (i *Application) SetMaintenanceMode(down bool)

SetMaintenanceMode 更新应用维护状态。

func (*Application) ShowProviders

func (i *Application) ShowProviders()

func (*Application) ShowSubApps

func (i *Application) ShowSubApps()

func (*Application) Terminate

func (i *Application) Terminate(ctx context.Context) error

func (*Application) Terminating

func (i *Application) Terminating(callback interface{}) foundation.Application

func (*Application) Version

func (i *Application) Version() string

func (*Application) WebShell

func (i *Application) WebShell() error

WebShell 使用 Web 壳启动系统。

type Installable

type Installable interface {
	service.Interface
	GetBinName() string
	GetDisplayName() string
	GetDescription() string
	GetVersion() string
}

type ServiceCommandGetter

type ServiceCommandGetter struct {
	// contains filtered or unexported fields
}

func (*ServiceCommandGetter) Lang

func (i *ServiceCommandGetter) Lang()

type SubApp

type SubApp interface {
	Name() string
	RegisterRouters()
	ServiceProviders() []foundation.ServiceProvider
	Binds() []any
	Menu() []*router.Menu
	Commands() []*cobra.Command
	// Bootstrap 应用启动前执行,如初始化配置,初始化数据,初始化表结构等
	Bootstrap()
}

SubApp 子应用

Source Files

  • application.go
  • service_installer.go

Directories

Path Synopsis
log
pay
core
di
provider
db
log
runtime
cmd
testing
tooling
cmd/checkdeps command
cmd/harbor command
file: url_match.go Package urlmatch 提供与 Gin 路由语义一致的 URL 匹配工具(对称匹配)
file: url_match.go Package urlmatch 提供与 Gin 路由语义一致的 URL 匹配工具(对称匹配)
structs
Package structs contains various utilities functions to work with structs.
Package structs contains various utilities functions to work with structs.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL