goinfras

package module
v1.2.8 Latest Latest
Warning

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

Go to latest
Published: Jan 30, 2021 License: MIT Imports: 15 Imported by: 0

README

Goinfras

Goinfras是一个后端应用基础设施的资源组件启动器,其实现了一些后端常用的组件客户端或工具,并提供可执行的实例。 使用goinfras,你只需要在项目中注册所需要的组件,并编写所需要的配置信息,最后让Application启动即可使用。

实现的资源组件:
用例

简单项目模板项目: https://github.com/bb-orz/goapp-sample

通用账户项目模板: https://github.com/bb-orz/goapp-account

使用启动器项目,您只需做如下步骤:

Step 1:注册您所需要的启动器
import (
	"github.com/bb-orz/goinfras"
	"github.com/bb-orz/goinfras/XCron"
	"github.com/bb-orz/goinfras/XEtcd"
	"github.com/bb-orz/goinfras/XLogger"
	"github.com/bb-orz/goinfras/XMQ/XNats"
	"github.com/bb-orz/goinfras/XMQ/XRedisPubSub"
	"github.com/bb-orz/goinfras/XOAuth"
	"github.com/bb-orz/goinfras/XOss/XAliyunOss"
	"github.com/bb-orz/goinfras/XOss/XQiniuOss"
	"github.com/bb-orz/goinfras/XStore/XGorm"
	"github.com/bb-orz/goinfras/XStore/XMongo"
	"github.com/bb-orz/goinfras/XStore/XRedis"
	"github.com/bb-orz/goinfras/XValidate"
	"github.com/gin-gonic/gin"

	_ "github.com/bb-orz/goapp-sample/simple/core" // 自动载入核心业务逻辑注册
	_ "github.com/bb-orz/goapp-sample/simple/restful" // 自动载入Restful 模块路由注册
	"github.com/bb-orz/goinfras/XGin"
)

// 注册应用组件启动器,把基础设施各资源组件化
func RegisterStarter(viperCfg *viper.Viper) {
	
	goinfras.RegisterStarter(XLogger.NewStarter())

	// 注册Cron定时任务
	// 可以自定义一些定时任务给starter启动
	goinfras.RegisterStarter(XCron.NewStarter())

	// 注册ETCD
	goinfras.RegisterStarter(XEtcd.NewStarter())

	// 注册mongodb启动器
	goinfras.RegisterStarter(XMongo.NewStarter())

	// 注册mysql启动器
	goinfras.RegisterStarter(XGorm.NewStarter())
	// 注册Redis连接池
	goinfras.RegisterStarter(XRedis.NewStarter())
	// 注册Oss
	goinfras.RegisterStarter(XAliyunOss.NewStarter())
	goinfras.RegisterStarter(XQiniuOss.NewStarter())
	// 注册Mq
	goinfras.RegisterStarter(XNats.NewStarter())
	goinfras.RegisterStarter(XRedisPubSub.NewStarter())
	// 注册Oauth Manager
	goinfras.RegisterStarter(XOAuth.NewStarter())


	// 注册gin web 服务启动器
	// TODO add your gin middlewares
	middlewares := make([]gin.HandlerFunc, 0)
	goinfras.RegisterStarter(XGin.NewStarter(middlewares...))

	// 注册验证器
	goinfras.RegisterStarter(XValidate.NewStarter())

	// 对资源组件启动器进行排序
	goinfras.SortStarters()

}
Step 2:选择您的web引擎:gin/echo,定义相应的接口并在包初始化时注册接口路由
func init() {
	// 初始化时自动注册该API到Gin Engine
	XGin.RegisterApi(new(SimpleApi))
}

type SimpleApi struct {
	service1 services.IService1
}

// SetRouter由Gin Engine 启动时调用
func (s *SimpleApi) SetRoutes() {
	s.service1 = services.GetService1()

	engine := XGin.XEngine()

	engine.GET("simple/foo", s.Foo)
	engine.GET("simple/bar", s.Bar)
}

func (s *SimpleApi) Foo(ctx *gin.Context) {
	email := ctx.Param("email")
	// 调用服务
	err := s.service1.Foo(services.InDTO{Email: email})

	// 处理错误
	fmt.Println(err)
}

func (s *SimpleApi) Bar(ctx *gin.Context) {
	email := ctx.Param("email")
	// 调用服务
	err := s.service1.Bar(services.InDTO{Email: email})

	// 处理错误
	fmt.Println(err)
}


Step 3:创建应用并启动
var app *goinfras.Application // 应用实例

func main() {
	// 初始化Viper配置加载器,导入配置,启动参数由命令行flag输入
	fmt.Println("Viper Config Loading  ......")
	viperCfg := goinfras.ViperLoader()

	// 注册应用组件启动器
	fmt.Println("Register Starters  ......")
	RegisterStarter(viperCfg)

	// 创建应用程序启动管理器
	app = goinfras.NewApplication(viperCfg)

	// 运行应用,启动已注册的资源组件
	fmt.Println("Application Starting ......")
	app.Up()
}
Step4:确定你的配置信息,可通过环境变量、配置文件或远程配置中心设置

本项目提供模板配置文件供参考:example.yaml

运行goinfras的项目需注意:

  • 使用goinfras.ViperLoader(),载入初始viper配置实例时,默认接收以下命令行参数,获取viper实例初始配置:
    • -f :Config file flag,like: -f ../config/config.yaml
    • -P : Remote K/V config flag, system provider,support etcd/consul. like: -P=etcd
    • -E : Remote K/V config flag, system endpoint,etcd requires http://ip:port consul requires ip:port
    • -K : Remote K/V config flag, k is the path in the k/v store to retrieve configuration,like: -K /configs/myapp.json"
    • -T : Remote K/V config flag, upport: 'json', 'toml', 'yaml', 'yml', 'properties', 'props', 'prop', 'env', 'dotenv'. like: -T=json
    • -D : Remote K/V config flag, Currently, only tested with etcd support
    • -a : ENV config flag, enable automatic, like: -a=true
    • -e : ENV config flag, allow env empty,like: -e=false
    • -p : ENV config flag, env prefix,like: -p=goinfras_
    • -k : ENV config flag, env keys,like: -k=aaa -k=bbb
Step5:构建并启动
cd {YourProject}/app
go build


// 启动
./app -f=../config/example.yaml

==================StdOut====================
Viper Config Loading  ......
Viper File Config Was Loaded  ......
Register Starters  ......
Sorted Starters:
XLogger Starter Attention!
XAliyunOss Starter Attention!
XEtcd Starter Attention!
XMongo Starter Attention!
XGorm Starter Attention!
XRedis Starter Attention!
XCron Starter Attention!
XQiniuOss Starter Attention!
XNats Starter Attention!
XRedisPubSub Starter Attention!
XOAuth Starter Attention!
XGin Starter Attention!
XValidate Starter Attention!
Application Starting ......

......

[GIN-debug] Listening and serving HTTP on 127.0.0.1:8090


工具

gt https://github.com/bb-orz/gt

gt 是一个go应用脚手架生成工具,它会帮助您初始化一个应用程序脚手架,其内置一些代码生成命令,可帮您生成model/domain/service/restful/rpc/starter等代码模板,极大的提高您的开发效率。

Documentation

Index

Constants

View Source
const (
	KeyConfig = "_vpcfg"
	KeyLogger = "_logger"
	KeyGlobal = "_global"
)
View Source
const (
	Env      = "env"      // 允许环境:dev、testing、product
	Host     = "host"     // 主机地址
	Endpoint = "endpoint" // 节点
	AppName  = "appname"  // 应用名
	Version  = "version"  // 应用版本
)

初始全局配置

View Source
const (
	ConfigFilePathFlag = "config_file"

	RemoteProviderFlag      = "remote_provider"
	RemoteEndpointFlag      = "remote_endpoint"
	RemoteKVPathFlag        = "remote_kv_path"
	RemoteTypeFlag          = "remote_type"
	RemoteWatchDurationFlag = "remote_watch_duration"

	EnvPrefixFlag     = "env_prefix"
	EnvKeysFlag       = "env_keys"
	EnvAllowEmptyFlag = "env_allow_empty"
	EnvAutomaticFlag  = "env_automatic"
)
View Source
const (
	StepInit  = "Init"
	StepSetup = "Setup"
	StepStart = "Start"
	StepCheck = "Check"
	StepStop  = "Hook"
)

启动步骤常量

View Source
const (
	DebugLevel   = "Debug"
	InfoLevel    = "Info"
	OKLevel      = "OK"
	WarningLevel = "Warning"
	ErrorLevel   = "Error"
	FailLevel    = "Fail"
)

日志等级命名常量

View Source
const (
	BasicGroup     PriorityGroup = 30 // 基础组件级别,适用设置优先启动的组件,如日志等
	ResourcesGroup PriorityGroup = 20 // 资源组件级别,适用设置项目需要的外围资源组件优先级,如数据库连接池等
	AppGroup       PriorityGroup = 10 // 应用组件级别,适用设置应用程序启动或运行时启动的组件,如web引擎、数据传输对象验证器、JWT 令牌验证工具等

	INT_MAX          = int(^uint(0) >> 1) // 最优先启动级别
	INT_MIN          = 0                  // 最末位启动级别
	DEFAULT_PRIORITY = 100                // 默认
)
View Source
const (
	StarterPosition = "Starter"
)

记录位置命名常量

Variables

View Source
var StarterManager = new(starterManager)
View Source
var (
	ViperCfg *viper.Viper // viper 配置实例

)

Functions

func Check

func Check(a interface{}) error

结构体指针检查验证,如果传入的interface为nil,就通过log.Panic函数抛出一个异常,它被用在starter中检查组件资源是否已启动

func LoadViperConfigFromEnv

func LoadViperConfigFromEnv(viperCfg *viper.Viper, envPrefix string, envKeys []string, envAllowEmpty, envAutomatic bool, envKeyReplacer *strings.Replacer) error

Viper读取环境变量 *

  • @Description: Viper读取环境变量
  • @param viperCfg Viper实例
  • @param envPrefix 指定需读取的环境变量前缀
  • @param envKeys 绑定特定环境变量
  • @param envAllowEmpty 是否允许读取空值的环境变量
  • @param envAutomatic 是否载入所有环境变量,如设置Prefix,则只筛选有前缀的载入
  • @param envKeyReplacer 键名字符替换器,常用语替换键名连接符
  • @return error

func LoadViperConfigFromFile

func LoadViperConfigFromFile(viperCfg *viper.Viper, configFilePath string) error

*

  • @Description: Viper 读取配置文件
  • @param viperCfg Viper实例
  • @param configFilePath 配置文件路径及文件名
  • @return error

func LoadViperConfigFromRemote

func LoadViperConfigFromRemote(viperCfg *viper.Viper, remoteProvider, remoteEndpoint, remotePath, remoteType string, etcdWatchDuration time.Duration) error

*

  • @Description: Viper 读取远程配置系统
  • @param viperCfg Viper实例
  • @param remoteProvider 远程配置提供者etcd/consult
  • @param remoteEndpoint 远程配置主机节点
  • @param remotePath 远程配置键节点
  • @param remoteType 因为在字节流中没有文件扩展名,所以这里需要设置下类型。支持的扩展名有 "json", "toml", "yaml", "yml", "properties", "props", "prop", "env", "dotenv"
  • @param etcdWatchDuration etcd watch 监听时间间隔
  • @return error

func NotifySignal

func NotifySignal(logger IStarterLogger)

应用启动时监听系统信号:停止和退出时只需关闭回调

func OpenFile added in v1.2.2

func OpenFile(fileName string, flag int, perm os.FileMode) (*os.File, error)

func Register

func Register(name string, fn func())

func RegisterStarter

func RegisterStarter(s Starter)

开放启动注册器

func SortStarters

func SortStarters()

组件启动器排序

func ViperLoader

func ViperLoader() *viper.Viper

Types

type Application

type Application struct {
	Sctx *StarterContext // 应用启动器上下文
}

应用程序启动管理器

func NewApplication

func NewApplication(vpcfg *viper.Viper) *Application

创建应用程序启动管理器

func NewApplicationWithStarterLoggerWriter

func NewApplicationWithStarterLoggerWriter(vpcfg *viper.Viper, logWriters ...io.Writer) *Application

创建一个带输出启动日志的应用管理器

func XApp added in v1.1.6

func XApp() *Application

获取应用实例的方法,通过App实例可在项目内部获取启动器上下文,包括启动配置信息等

func (*Application) Down

func (app *Application) Down()

停止或销毁应用程序所有基础资源

func (*Application) Up

func (app *Application) Up()

启动应用程序所有基础资源 (初始化 -> 安装 -> 检查 -> 启动 -> 监听系统退出信号)

type BaseStarter

type BaseStarter struct{}

基础空启动器,可便于被其他具体的基础资源嵌入

func (*BaseStarter) Check

func (*BaseStarter) Check(*StarterContext) bool

组件启动状态检查

func (*BaseStarter) Init

func (*BaseStarter) Init(*StarterContext)

载入启动器配置信息

func (*BaseStarter) Name

func (*BaseStarter) Name() string

func (*BaseStarter) Priority

func (s *BaseStarter) Priority() int

为资源组件设置启动优先值

func (*BaseStarter) PriorityGroup

func (s *BaseStarter) PriorityGroup() PriorityGroup

为资源组件设置优先组

func (*BaseStarter) Setup

func (*BaseStarter) Setup(*StarterContext)

安装作为系统资源组件

func (*BaseStarter) Start

func (*BaseStarter) Start(*StarterContext)

如需随应用运行需Start启动

func (*BaseStarter) StartBlocking

func (*BaseStarter) StartBlocking() bool

阻塞型组件需设置为true

func (*BaseStarter) Stop

func (*BaseStarter) Stop() error

关闭应用时的资源组件清理工作

type CommandLineStarterLogger

type CommandLineStarterLogger struct {
	StarterLogger
}

标准颜色输出日志记录器

func NewCommandLineStarterLogger

func NewCommandLineStarterLogger(env string) *CommandLineStarterLogger

针对终端输出的默认启动日志记录器

type CommonStarterLogger

type CommonStarterLogger struct {
	StarterLogger
}

通用启动日志记录器(输出到终端和启动日志文件)

func NewStarterLoggerWithWriters

func NewStarterLoggerWithWriters(env string, writers ...io.Writer) *CommonStarterLogger

type Global added in v1.2.4

type Global map[string]interface{}

func NewGlobal added in v1.2.4

func NewGlobal(vpcfg *viper.Viper) Global

func (Global) Get added in v1.2.4

func (g Global) Get(k string) interface{}

func (Global) GetAppName added in v1.2.4

func (g Global) GetAppName() string

func (Global) GetEndpoint added in v1.2.4

func (g Global) GetEndpoint() string

func (Global) GetEnv added in v1.2.4

func (g Global) GetEnv() string

func (Global) GetHost added in v1.2.4

func (g Global) GetHost() string

func (Global) GetVersion added in v1.2.4

func (g Global) GetVersion() string

func (Global) Set added in v1.2.4

func (g Global) Set(k string, v interface{})

type IStarterLogger

type IStarterLogger interface {
	Debug(name, step, msg string)
	Info(name, step, msg string)
	OK(name, step, msg string)
	Warning(name, step, msg string)
	Error(name, step string, err error)
	Fail(name, step string, err error)
}

type LogFormatter

type LogFormatter func(params LogFormatterParams) string

格式转化签名函数

type LogFormatterParams

type LogFormatterParams struct {
	Position  string    // 日志记录位置
	Name      string    // 启动器名称
	Step      string    // 启动器步骤
	LogLevel  string    // 记录日志级别
	TimeStamp time.Time // 记录时间戳
	Message   string    // 记录信息
}

格式化输出参数

func (*LogFormatterParams) LogLevelColor

func (p *LogFormatterParams) LogLevelColor() string

每种错误级别输出不同的颜色

func (*LogFormatterParams) LogPositionColor

func (p *LogFormatterParams) LogPositionColor() string

日志输出位置颜色标示

func (*LogFormatterParams) LogStepColor

func (p *LogFormatterParams) LogStepColor() string

启动器步骤颜色标示

func (*LogFormatterParams) ResetColor

func (p *LogFormatterParams) ResetColor() string

颜色重置

type PriorityGroup

type PriorityGroup int

启动组件顺序的优先组

type Starter

type Starter interface {
	// 组件名
	Name() string
	// 初始化:资源组件读取配置信息
	Init(sctx *StarterContext)
	// 安装:检查该组件的前置依赖
	Setup(sctx *StarterContext)
	// 启动:该资源组件的连接或启动以供应用程序后续使用
	Start(sctx *StarterContext)
	// 启动状态检查
	Check(sctx *StarterContext) bool
	// 阻塞启动:设置需要后置启动的资源组件,默认为false
	StartBlocking() bool
	// 资源停止:
	// 通常在启动时遇到异常时或者启用远程管理时,用于释放资源和终止资源的使用,
	// 通常要优雅的释放,等待正在进行的任务继续,但不再接受新的任务
	Stop() error
	// 优先组:从高到低分:系统级别、基本资源级别、应用级别三组
	PriorityGroup() PriorityGroup
	// 设置该资源组件的启动优先级,默认为DEFAULT_PRIORITY,最大为INT_MAX
	Priority() int
}

启动器接口

type StarterContext

type StarterContext map[string]interface{}

资源启动器上下文,用来在服务资源初始化、安装、启动和停止的生命周期中变量和对象的传递

func CreateDefaultStarterContext

func CreateDefaultStarterContext(vpcfg *viper.Viper, logger IStarterLogger) *StarterContext

创建一个默认最少配置启动器上下文

func (StarterContext) Configs

func (s StarterContext) Configs() *viper.Viper

func (StarterContext) Global added in v1.2.4

func (s StarterContext) Global() Global

func (StarterContext) Item added in v1.1.6

func (s StarterContext) Item(key string) interface{}

func (StarterContext) Logger

func (s StarterContext) Logger() IStarterLogger

func (StarterContext) PassError

func (s StarterContext) PassError(name, step string, err error) bool

err == nil 返回 true,否则记录启动器错误日志并返回false

func (StarterContext) PassFail

func (s StarterContext) PassFail(name, step string, err error) bool

err == nil,返回true ;err != nil 致命错误处理,直接panic

func (StarterContext) PassWarning

func (s StarterContext) PassWarning(name, step string, err error) bool

有错误则记录启动器警告日志

func (StarterContext) SetConfigs

func (s StarterContext) SetConfigs(vpcfg *viper.Viper)

func (StarterContext) SetGlobal added in v1.2.4

func (s StarterContext) SetGlobal(g Global)

func (StarterContext) SetItem added in v1.1.6

func (s StarterContext) SetItem(key string, item interface{})

func (StarterContext) SetLogger

func (s StarterContext) SetLogger(logger IStarterLogger)

type StarterLogger

type StarterLogger struct {
	Outputs []*StarterLoggerOutput
	// contains filtered or unexported fields
}

启动器日志记录器

func (*StarterLogger) Debug added in v1.2.0

func (l *StarterLogger) Debug(name, step, msg string)

func (*StarterLogger) Error added in v1.2.0

func (l *StarterLogger) Error(name, step string, err error)

func (*StarterLogger) Fail added in v1.2.0

func (l *StarterLogger) Fail(name, step string, err error)

func (*StarterLogger) Info added in v1.2.0

func (l *StarterLogger) Info(name, step, msg string)

func (*StarterLogger) OK added in v1.2.0

func (l *StarterLogger) OK(name, step, msg string)

func (*StarterLogger) Warning added in v1.2.0

func (l *StarterLogger) Warning(name, step, msg string)

type StarterLoggerOutput

type StarterLoggerOutput struct {
	Formatter LogFormatter // 格式转化器
	Writers   io.Writer    // 输出
}

可定义多个输出

Jump to

Keyboard shortcuts

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