giu

package module
v0.0.0-...-9e4d0e2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2023 License: MIT Imports: 25 Imported by: 0

README

go-init-utils

Competitive programming utility library for go It is not a framework, just a set of utilities, so you can use it with any other framework.
This library is inspired by [go-spring], but in go style rather than java style.

基本理念 对常见的库进行interface封装,让这些interface之间互相配套和适配 同时,提供一些对这些库进行简易初始化的方法 然后,给出使用不同的ioc框架进行初始化的方法,暂定uber的fx和google的wire 最底层的依赖interface: config, logger, metrics 然后数据相关的: gorm redis influxdb kafka 插入一些简单的工具件: http client 然后是server相关的: gin grpc

Documentation

Index

Constants

View Source
const (
	CRON_CONCURRENT_MODE_CONCURRENT int = iota
	CRON_CONCURRENT_MODE_SKIP
	CRON_CONCURRENT_MODE_DELAY
)
View Source
const (
	GORM_DRIVER_MYSQL      = "mysql"
	GORM_DRIVER_PG         = "postgres"
	GORM_DRIVER_PG_SHORTEN = "pg"
	GORM_DRIVER_SQLITE     = "sqlite"
	GORM_DRIVER_SQLSERVER  = "sqlserver"
)
View Source
const (
	LOG_LEVEL_DEBUG  = "debug"
	LOG_LEVEL_INFO   = "info"
	LOG_LEVEL_WARN   = "warn"
	LOG_LEVEL_ERROR  = "error"
	LOG_LEVEL_PANIC  = "panic"
	LOG_LEVEL_DPANIC = "dpanic"
	LOG_LEVEL_FATAL  = "fatal"
)

Variables

View Source
var (
	ERR_LOGGER_NOT_INIT = errors.New("logger is nil, please init logger first")
)
View Source
var GIN_TRACE_ID = "X-Trace-Id"

Functions

func AddCronJob

func AddCronJob(c *cron.Cron, jobs []*CronJob) []cron.EntryID

func DefaultConfig

func DefaultConfig() (*viper.Viper, error)

func DefaultGorm

func DefaultGorm() (*gorm.DB, error)

func DefaultRedis

func DefaultRedis() redis.UniversalClient

func DefaultResty

func DefaultResty() *resty.Client

func DefaultSLogger

func DefaultSLogger() *slog.Logger

func DefaultZapLogger

func DefaultZapLogger() *zap.Logger

func Manually

func Manually()

func NewClusterRedis

func NewClusterRedis(addrs []string) redis.UniversalClient

func NewConfigFromRemote

func NewConfigFromRemote(params RemoteConfigParams) (*viper.Viper, error)

func NewCron

func NewCron(params CronParams) *cron.Cron

func NewCronJob

func NewCronJob(params CronJob) cron.Job

func NewFailOverRedisClient

func NewFailOverRedisClient(addrs []string, masterName string) redis.UniversalClient

func NewGinMiddlewareJsonLogger

func NewGinMiddlewareJsonLogger(l *zap.Logger) gin.HandlerFunc

NewGinMiddlewareJsonLogger returns a gin middleware for logging json request and response.

func NewGinMiddlewareRecovery

func NewGinMiddlewareRecovery(zl *zap.Logger) gin.HandlerFunc

NewGinMiddlewareRecovery returns a gin middleware for recovery with zap logger.

func NewGinMiddlewareTrace

func NewGinMiddlewareTrace() gin.HandlerFunc

NewGinMiddlewareTrace returns a gin middleware for adding trace id to request header.

func NewGinWithLogger

func NewGinWithLogger(zl *zap.Logger) *gin.Engine

func NewGorm

func NewGorm(params GormConnectionParams, configParams ...*GormConfigParams) (*gorm.DB, error)

func NewGormMysql

func NewGormMysql(params GormConnectionParams) gorm.Dialector

func NewGormPostgres

func NewGormPostgres(params GormConnectionParams) gorm.Dialector

func NewGormSQLServer

func NewGormSQLServer(params GormConnectionParams) gorm.Dialector

func NewGormSQLite

func NewGormSQLite(params GormConnectionParams) gorm.Dialector

func NewGormWithLogger

func NewGormWithLogger(params GormConnectionParams, zl *zap.Logger, configParams ...*GormConfigParams) (*gorm.DB, error)

func NewLocalConfig

func NewLocalConfig(params ConfigParams) (*viper.Viper, error)

func NewRedis

func NewRedis(options *redis.UniversalOptions) redis.UniversalClient

func NewResty

func NewResty(options *RestyParams) *resty.Client

func NewRestyWithLogger

func NewRestyWithLogger(options *RestyParams, logger *zap.Logger) *resty.Client

func NewSLogger

func NewSLogger(params LoggerParams) *slog.Logger

func NewSchedule

func NewSchedule(params ScheduleParams) (cron.Schedule, error)

NewSchedule creates a new Schedule.

func NewStandaloneRedis

func NewStandaloneRedis(addrs string) redis.UniversalClient

func NewZapLogger

func NewZapLogger(params *LoggerParams) *zap.Logger

Types

type ConfigParams

type ConfigParams struct {
	ConfigName string
	ConfigType string
	ConfigPath []string
	AutoEnv    bool
}

type CronJob

type CronJob struct {
	Schedule cron.Schedule
	Func     func()
}

func (*CronJob) Run

func (cj *CronJob) Run()

type CronParams

type CronParams struct {
	ConcurrentMode int
	Location       string
}

type GiuConfig

type GiuConfig[ExtendParams any] struct {
	Logger         map[string]*LoggerParams         `mapstructure:"logger"`
	GormConfig     *GormConfigParams                `mapstructure:"gorm_config"`
	GormConnection map[string]*GormConnectionParams `mapstructure:"gorm_connection"`
	Redis          map[string]*RedisParams          `mapstructure:"redis"`
	Extend         ExtendParams                     `mapstructure:"extend"`
}

type GiuProvider

type GiuProvider[T any] struct {
	// contains filtered or unexported fields
}

func NewGiuProvider

func NewGiuProvider[T any](items ...map[string]T) *GiuProvider[T]

NewGiuProvider creates a generic provider, if items is not empty, the first item will be set as default

func NewGiuProviderFromConfig

func NewGiuProviderFromConfig[T any, U any](config *viper.Viper, configKey string, newFunc func(U) T) (*GiuProvider[T], error)

NewGiuProviderFromConfig creates a generic provider with item init function and read the init params from viper config.

func NewGiuProviderFromConfigError

func NewGiuProviderFromConfigError[T any, U any](config *viper.Viper, configKey string, newFunc func(U) (T, error)) (*GiuProvider[T], error)

NewGiuProviderWithLoggerFromConfig creates a generic provider with item init function and read the init params from viper config. The function may return an error.

func NewGiuProviderFromParams

func NewGiuProviderFromParams[T any, U any](newFunc func(U) T, params map[string]U) *GiuProvider[T]

NewGiuProviderWithLogger creates a generic provider with item init function and the params used in the init function

func NewGiuProviderFromParamsError

func NewGiuProviderFromParamsError[T any, U any](newFunc func(U) (T, error), params map[string]U) (*GiuProvider[T], error)

NewGiuProviderWithLogger creates a generic provider with item init function and the params used in the init function. The init function may return an error.

func NewGiuProviderWithLoggerFromConfig

func NewGiuProviderWithLoggerFromConfig[T any, U any](config *viper.Viper, configKey string, newFunc func(U, *zap.Logger) T, logger *zap.Logger) (*GiuProvider[T], error)

NewGiuProviderWithLoggerFromConfig creates a generic provider with item init function and read the init params from viper config. The item needs a zap logger to init.

func NewGiuProviderWithLoggerFromConfigError

func NewGiuProviderWithLoggerFromConfigError[T any, U any](config *viper.Viper, configKey string, newFunc func(U, *zap.Logger) (T, error), logger *zap.Logger) (*GiuProvider[T], error)

NewGiuProviderWithLoggerFromConfig creates a generic provider with item init function and read the init params from viper config. The function needs a zap logger to init and may return an error.

func NewGiuProviderWithLoggerFromParams

func NewGiuProviderWithLoggerFromParams[T any, U any](newFunc func(U, *zap.Logger) T, params map[string]U, logger *zap.Logger) *GiuProvider[T]

NewGiuProviderWithLogger creates a generic provider with item init function and the params used in the init function. The item needs a zap logger to init, so the logger is also passed in.

func NewGiuProviderWithLoggerFromParamsError

func NewGiuProviderWithLoggerFromParamsError[T any, U any](newFunc func(U, *zap.Logger) (T, error), params map[string]U, logger *zap.Logger) (*GiuProvider[T], error)

NewGiuProviderWithLogger creates a generic provider with item init function and the params used in the init function. The init function needs a logger and it may return an error.

func (*GiuProvider[T]) Add

func (p *GiuProvider[T]) Add(name string, d T, isDefault ...bool)

Add adds a value to the generic provider

func (*GiuProvider[T]) Default

func (p *GiuProvider[T]) Default() T

Default returns the default value of the generic provider, if no default value is set, it returns the first value

func (*GiuProvider[T]) Get

func (p *GiuProvider[T]) Get(name string) (T, bool)

Get returns the value of the generic provider, if the name is not found, it returns false

func (*GiuProvider[T]) SetDefault

func (p *GiuProvider[T]) SetDefault(name string) bool

SetDefault sets the default value of the generic provider, if the name is not found, it returns false

func (*GiuProvider[T]) Shutdown

func (p *GiuProvider[T]) Shutdown() error

Shutdown is a placeholder for the generic provider, it should be implemented by the specific provider

type GormConfigParams

type GormConfigParams struct {
	*gorm.Config
	LogLevel string
}

type GormConnectionParams

type GormConnectionParams struct {
	Driver   string
	Host     string
	Port     uint
	User     string
	Password string
	Database string
}

type GormProvider

type GormProvider interface {
	Provider[*gorm.DB]
}

func NewGormProvider

func NewGormProvider(connections ...map[string]*gorm.DB) GormProvider

NewGormProvider creates a gorm provider from existing connection, if items is not empty, the first item will be set as default

func NewGormProviderFromConfig

func NewGormProviderFromConfig(config *viper.Viper) (GormProvider, error)

NewGormProviderFromConfig creates a gorm provider from viper config and GiuConfig struct, if items is not empty, the first item will be set as default

func NewGormProviderFromParams

func NewGormProviderFromParams(configParams *GormConfigParams, connectionParams map[string]*GormConnectionParams) (GormProvider, error)

NewGormProviderFromParams creates a gorm provider from params, if items is not empty, the first item will be set as default

func NewGormProviderWithLoggerFromConfig

func NewGormProviderWithLoggerFromConfig(config *viper.Viper, logger *zap.Logger) (GormProvider, error)

NewGormProviderWithLoggerFromConfig creates a gorm provider from viper config and GiuConfig struct and replace default logger with zap logger, if items is not empty, the first item will be set as default

type LoggerParams

type LoggerParams struct {
	LogName   string // log file name with path
	LogLevel  string // log level: info, debug, warn, error, dpanic, panic, fatal
	MaxSize   int    // size in megabytes
	MaxBackup int    // max backup files
	MaxAge    int    // max age in days
	Compress  bool   // compress
	Tag       string // log tag
}

type Provider

type Provider[T any] interface {
	Add(name string, d T, isDefault ...bool)
	Get(name string) (T, bool)
	Default() T
	SetDefault(name string) bool
	Shutdown() error
}

func NewProvider

func NewProvider[T any](items ...map[string]T) Provider[T]

NewProvider creates a generic provider, if items is not empty, the first item will be set as default

func NewRedisProvider

func NewRedisProvider(clients ...map[string]redis.UniversalClient) Provider[redis.UniversalClient]

NewRedisProvider creates a redis provider from existing connection, if items is not empty, the first item will be set as default

func NewRedisProviderFromConfig

func NewRedisProviderFromConfig(config *viper.Viper) (Provider[redis.UniversalClient], error)

NewRedisProviderFromConfig creates a redis provider from viper config and GiuConfig struct, if items is not empty, the first item will be set as default. NOTE: it's not a good idea to log redis cmd, so we don't use zap logger here.

func NewRedisProviderFromParams

func NewRedisProviderFromParams(params map[string]*RedisParams) Provider[redis.UniversalClient]

NewRedisProviderFromParams creates a redis provider from params, if items is not empty, the first item will be set as default

type RedisParams

type RedisParams = redis.UniversalOptions

type RedisProvider

type RedisProvider interface {
	Provider[redis.UniversalClient]
}

type RemoteConfigParams

type RemoteConfigParams struct {
	Provider   string
	Endpoint   string
	Path       string
	ConfigType string
	AutoEnv    bool
}

type RestyParams

type RestyParams struct {
	// Timeout is the amount of time to wait for a response.
	Timeout time.Duration
	// RetryTimes is the number of times to retry.
	RetryTimes int
	// DebugMode is the flag to enable/disable debug mode. It will print the request/response details.
	// It will print in debug level.
	DebugMode bool
	// StructLog is the flag to enable/disable simple request&response struct log. It's only work when resty is init with zap logger.
	// When it's enabled, it will set debug mode to true. Struct log will print in info level.
	StructLog bool
}

type ScheduleParams

type ScheduleParams struct {
	Tag         string
	Schedule    string
	WithSeconds bool
}

type Set

type Set[T any] struct {
	Name  string
	Value T
}

func MapToSet

func MapToSet[T any](m map[string]T) []Set[T]

type ZapGormLogger

type ZapGormLogger struct {
	SlowThreshold             time.Duration
	SkipCallerLookup          bool
	IgnoreRecordNotFoundError bool
	TraceWarnStr              string
	TraceErrStr               string
	TraceStr                  string
	// contains filtered or unexported fields
}

func NewZapGormLogger

func NewZapGormLogger(zl *zap.Logger, logLevel string) *ZapGormLogger

func (*ZapGormLogger) Error

func (z *ZapGormLogger) Error(ctx context.Context, msg string, data ...interface{})

func (*ZapGormLogger) Info

func (z *ZapGormLogger) Info(ctx context.Context, msg string, data ...interface{})

func (*ZapGormLogger) LogMode

func (z *ZapGormLogger) LogMode(level logger.LogLevel) logger.Interface

func (*ZapGormLogger) Trace

func (l *ZapGormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error)

func (*ZapGormLogger) Warn

func (z *ZapGormLogger) Warn(ctx context.Context, msg string, data ...interface{})

type ZapLogger

type ZapLogger struct {
	*zap.Logger
}

func (*ZapLogger) Printf

func (zl *ZapLogger) Printf(ctx context.Context, format string, v ...interface{})

type ZapProvider

type ZapProvider interface {
	Provider[*zap.Logger]
}

func NewZapProvider

func NewZapProvider(loggers ...map[string]*zap.Logger) ZapProvider

NewZapProvider creates a zap provider from existing logger, if items is not empty, the first item will be set as default

func NewZapProviderFromConfig

func NewZapProviderFromConfig(config *viper.Viper) (ZapProvider, error)

NewZapProviderFromConfig creates a zap provider from viper config and GiuConfig struct, if items is not empty, the first item will be set as default

func NewZapProviderFromParams

func NewZapProviderFromParams(params map[string]*LoggerParams) ZapProvider

NewZapProviderFromParams creates a zap provider from params, if items is not empty, the first item will be set as default

Jump to

Keyboard shortcuts

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