common

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Index

Constants

View Source
const (
	FILE_TYPE_IMAGE int32 = 3
	FILE_TYPE_FILE  int32 = 4
	FILE_TYPE_AUDIO int32 = 5
	FILE_TYPE_MEDIA int32 = 6
)

Variables

View Source
var SnowflakeUtil = (*idgen.Snowflake)(nil)

SnowflakeUtil is the package-level snowflake generator, initialised on load. Deprecated: use idgen.SnowflakeNext / idgen.SnowflakeNextUint directly.

Functions

func BytesToString added in v0.2.0

func BytesToString(b []byte) string

BytesToString bytes to string Zero-copy

func CalculateFileHash added in v0.2.0

func CalculateFileHash(filePath string) (string, error)

CalculateFileHash 计算文件的SHA1哈希

func ClampSnowflakeUint

func ClampSnowflakeUint(id uint) uint

ClampSnowflakeUint clears the sign bit so IDs remain scannable from signed INTEGER columns. Deprecated: use idgen.ClampSnowflakeUint.

func ConfigureConnectionPool

func ConfigureConnectionPool(db *gorm.DB)

ConfigureConnectionPool configures the database connection pool. Overrides via env (positive ints only):

DB_MAX_OPEN_CONNS  (default: postgres 40, others 200)
DB_MAX_IDLE_CONNS  (default: postgres 20, others 50)
DB_CONN_MAX_LIFETIME  (Go duration, default 1h)
DB_CONN_MAX_IDLE_TIME (Go duration, default 30m)

func CopyFile added in v0.2.0

func CopyFile(src, dst string) error

CopyFile 复制文件

func Difference added in v0.2.0

func Difference[T comparable](slice1, slice2 []T) []T

Difference get difference set slice1-intersection

func EnsureDirectory added in v0.2.0

func EnsureDirectory(path string) error

EnsureDirectory 确保目录存在

func EnvDuration

func EnvDuration(key string) (time.Duration, bool)

EnvDuration reads a Go duration env var (e.g. "30m", "1h"). Returns (0, false) when unset/invalid.

func EnvFloat

func EnvFloat(key string) (float64, bool)

EnvFloat reads a float environment variable. Returns (0, false) when unset or invalid.

func EnvInt

func EnvInt(key string) (int, bool)

EnvInt reads an integer environment variable. Returns (0, false) when unset or invalid.

func FileExists added in v0.2.0

func FileExists(path string) bool

FileExists 检查文件是否存在

func GenerateID added in v0.2.0

func GenerateID() string

GenerateID 生成唯一的ID

func GetBoolEnv

func GetBoolEnv(key string) bool

func GetBoolOrDefault

func GetBoolOrDefault(key string, defaultValue bool) bool

GetBoolOrDefault gets boolean environment variable value, returns default if empty.

func GetContentType added in v0.2.0

func GetContentType(suffix string) (tp string)

func GetDistance added in v0.2.0

func GetDistance(lon1, lat1, lon2, lat2 float64) float64

Calculate distance between two points

func GetEnv

func GetEnv(key string) string

func GetFileSize added in v0.2.0

func GetFileSize(filePath string) (int64, error)

GetFileSize 获取文件大小

func GetFileType added in v0.2.0

func GetFileType(buf []byte) (fileType string)

func GetFileTypeBySuffix added in v0.2.0

func GetFileTypeBySuffix(suffix string) int32

func GetFloatEnv

func GetFloatEnv(key string) float64

func GetFloatEnvWithDefault

func GetFloatEnvWithDefault(key string, defaultValue float64) float64

GetFloatEnvWithDefault gets float environment variable with default value

func GetFloatOrDefault

func GetFloatOrDefault(key string, defaultValue float64) float64

GetFloatOrDefault gets float environment variable value, returns default if empty.

func GetIntEnv

func GetIntEnv(key string) int64

func GetIntEnvWithDefault

func GetIntEnvWithDefault(key string, defaultValue int) int

GetIntEnvWithDefault gets int environment variable with default value

func GetIntOrDefault

func GetIntOrDefault(key string, defaultValue int) int

GetIntOrDefault gets integer environment variable value, returns default if zero.

func GetStringOrDefault

func GetStringOrDefault(key, defaultValue string) string

GetStringOrDefault gets environment variable value, returns default if empty.

func InArray added in v0.2.0

func InArray[T comparable](needle T, haystack []T) bool

InArray check if element is in array

func InitDatabase

func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)

InitDatabase creates a GORM DB connection. If driver or dsn is empty, it falls back to environment variables DB_DRIVER / DSN.

func Intersect added in v0.2.0

func Intersect[T comparable](slice1, slice2 []T) []T

Intersect get intersection

func IsDirectory added in v0.2.0

func IsDirectory(path string) bool

IsDirectory 检查路径是否为目录

func IsFile added in v0.2.0

func IsFile(path string) bool

IsFile 检查路径是否为文件

func Join added in v0.2.0

func Join[T any](arg []T, str string) string

func LoadEnv

func LoadEnv(env string) error

LoadEnv loads a .env file into the process environment.

func LoadEnvs

func LoadEnvs(objPtr any)

LoadEnvs loads tagged env fields into a struct pointer.

func LookupEnv

func LookupEnv(key string) (value string, found bool)

func MakeMigrates

func MakeMigrates(db *gorm.DB, insts []any) error

MakeMigrates runs AutoMigrate for each instance.

func Merge added in v0.2.0

func Merge[T any](slice1, slice2 []T) []T

Merge get union

func NewSnowflake

func NewSnowflake() (*idgen.Snowflake, error)

NewSnowflake creates a snowflake generator using MACHINE_ID env var. Deprecated: use idgen.NewSnowflake.

func NextSnowflakeUint

func NextSnowflakeUint() uint

NextSnowflakeUint returns a snowflake id safe for uint + signed INTEGER stores. Deprecated: use idgen.SnowflakeNextUint.

func ParseDuration

func ParseDuration(s string, defaultVal time.Duration) time.Duration

ParseDuration parses duration string with default fallback.

func PositiveIntEnv

func PositiveIntEnv(key string) (int, bool)

PositiveIntEnv reads a strictly positive integer env var. Returns (0, false) when unset, invalid, or <= 0.

func PurgeEnvCacheForTest

func PurgeEnvCacheForTest()

PurgeEnvCacheForTest clears cached environment lookups. Tests that mutate process env via t.Setenv should call this in t.Cleanup when other tests wire components that read digest secrets from env.

func RemoveDirectory added in v0.2.0

func RemoveDirectory(path string) error

RemoveDirectory 删除目录

func RemoveFile added in v0.2.0

func RemoveFile(path string) error

RemoveFile 删除文件

func RunInitSQL added in v0.3.0

func RunInitSQL(db *gorm.DB, sqlFilePath string) error

RunInitSQL executes SQL statements from a local .sql file segment by segment (split by semicolon). Comment lines starting with -- or # and empty lines are skipped. Idempotent scripts should use IF NOT EXISTS in SQL for protection.

func StringToBytes added in v0.2.0

func StringToBytes(s string) []byte

StringToBytes string to bytes Zero-copy

func Unique added in v0.2.0

func Unique[T comparable](slice []T) []T

Unique remove duplicates from array

Types

type BaseModel

type BaseModel struct {
	ID        uint           `json:"id,string" gorm:"primaryKey;autoIncrement:false"`
	CreatedAt time.Time      `json:"createdAt" gorm:"autoCreateTime;comment:创建时间"`
	UpdatedAt time.Time      `json:"updatedAt,omitempty" gorm:"autoUpdateTime;comment:更新时间"`
	DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
	CreateBy  string         `json:"createBy,omitempty" gorm:"size:128;comment:创建人"`
	UpdateBy  string         `json:"updateBy,omitempty" gorm:"size:128;comment:更新人"`
	Remark    string         `json:"remark,omitempty" gorm:"size:128;comment:备注"`
}

BaseModel is embedded by all GORM entities in this package.

func (*BaseModel) BeforeCreate

func (m *BaseModel) BeforeCreate(tx *gorm.DB) error

BeforeCreate add snowflake id for base

func (*BaseModel) BeforeUpdate

func (m *BaseModel) BeforeUpdate(tx *gorm.DB) error

func (*BaseModel) Restore

func (m *BaseModel) Restore(operator string)

func (*BaseModel) SetCreateInfo

func (m *BaseModel) SetCreateInfo(operator string)

func (*BaseModel) SetUpdateInfo

func (m *BaseModel) SetUpdateInfo(operator string)

func (*BaseModel) SoftDelete

func (m *BaseModel) SoftDelete(operator string)

type QueryResult

type QueryResult struct {
	Value  any
	Value2 any
	Err    error
}

QueryResult is the synchronous result collected by Signals.Query. Handlers fill in Value/Value2/Err during Emit; the caller reads them after all handlers have returned.

type SigHandler

type SigHandler struct {
	ID      uint
	Handler SignalHandler
}

SigHandler pairs a unique handler ID with its callback.

type SignalHandler

type SignalHandler func(sender any, params ...any)

SignalHandler is a callback invoked when a signal event is emitted. sender is the originator of the event; params are arbitrary event data.

type Signals

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

Signals is a process-wide synchronous event bus.

Concurrency contract:

  • sigHandlers is copy-on-write. Connect/Disconnect never mutate a slice that a concurrent Emit may already be iterating; they publish a fresh slice instead. Emit can therefore snapshot under RLock and invoke handlers with the lock released.
  • Releasing the lock before invoking handlers is what makes reentrancy safe: handlers routinely Connect/Disconnect (notably one-shot handlers that unsubscribe themselves) and would otherwise self-deadlock.

func NewSignals

func NewSignals() *Signals

NewSignals creates a new Signals event bus.

func Sig

func Sig() *Signals

Sig returns the process-wide singleton Signals instance.

func (*Signals) Clear

func (s *Signals) Clear(events ...string)

Clear removes all handlers for the given events.

func (*Signals) Connect

func (s *Signals) Connect(event string, handler SignalHandler) uint

Connect registers a handler for the given event and returns its handler ID. The handler will be invoked on subsequent Emit calls for this event.

func (*Signals) Disconnect

func (s *Signals) Disconnect(event string, id uint)

Disconnect removes the handler with the given ID from the event.

func (*Signals) Emit

func (s *Signals) Emit(event string, sender any, params ...any)

Emit fires the event synchronously, calling all registered handlers in registration order. The lock is released before invoking handlers so that reentrant Connect/Disconnect is safe.

func (*Signals) Query

func (s *Signals) Query(event string, params ...any) *QueryResult

Query emits a signal and collects the synchronous result. The last parameter passed to handlers is *QueryResult, which handlers populate. The caller reads the returned result after all handlers return.

Directories

Path Synopsis
config module
idgen module
random module
response module
gin module

Jump to

Keyboard shortcuts

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