ling-baseling-base

根工具包 (common)

BaseModel、GORM 初始化、环境变量与文件工具

在线 Playground

在浏览器中直接体验本页相关 API,无需本地安装 Go 环境。

以下为 common 根包 README;子包文档见 通用工具索引

common

Root shared-utilities package for ling-base, plus 49 sub-packages covering caching, crypto, logging, rate limiting, and more.

Structure

common/
├── base.go           # BaseModel: GORM entity with snowflake ID + audit fields
├── env.go            # GetEnv / GetEnvXxx with TTL+LRU cache
├── dbs.go            # InitDatabase: GORM connection factory
├── dbs_mysql.go      # MySQL driver    (build tag: mysql)
├── dbs_pg.go         # PostgreSQL driver (build tag: pg)
├── dbs_sqlite.go     # SQLite fallback  (default build)
├── content_type.go   # File extension -> MIME type map
├── file_type.go      # File category constants (image/audio/media/file)
├── files.go          # File hash, size, save helpers
├── array.go          # Generic Join[T] helper
├── strings.go        # Zero-copy string <-> []byte conversions
├── geo.go            # Haversine distance between two coordinates
├── signals.go        # Signal/event handler registry
└── snowflake.go      # Deprecated snowflake aliases (use common/idgen)

Key Types

// BaseModel is embedded by all GORM entities.
type BaseModel struct {
    ID        uint           `gorm:"primaryKey"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt gorm.DeletedAt `gorm:"index"`
    CreateBy  string
    UpdateBy  string
    Remark    string
}

// InitDatabase creates a GORM DB from driver + DSN (falls back to env vars).
func InitDatabase(logWrite io.Writer, driver, dsn string) (*gorm.DB, error)

// GetEnv reads an env var with TTL+LRU caching.
func GetEnv(key string) string

Sub-packages (49)

PackageDescription
audioutilWAV/MP3 audio read, write, and decode utilities
barcode1D/2D barcode generation (Code128, EAN, PDF417, DataMatrix)
bloomUnified Bloom-filter interface (in-memory + distributed)
cacheGeneric Cache[K,V] interface with multiple backends
captchaCAPTCHA generation
circuitbreakerThread-safe circuit breaker (Closed/Open/Half-Open)
compressGzip and Zstd compression utilities
configMulti-format config loader (YAML + .env with env overrides)
constantsShared constants and env-var keys
convertType-safe conversions and JSON/TOML/YAML interconversion
cronCron expression parsing and next-fire-time calculation
cryptoAES (GCM/CBC), RSA, and JWT signing utilities
eventbusIn-memory pub/sub event bus (sync + async dispatch)
geoipIP geolocation lookup (domestic + international APIs)
hashMD5, SHA-1/256/512, HMAC-SHA256/512
i18nInternationalization helpers
idgenSnowflake + UUID v4 ID generation
imageutilImage processing utilities
jwtutilReusable JWT authentication layer on common/crypto
limiterUnified rate-limiting and concurrency-control interface
lockDistributed lock interface
loggerStructured logging (zap-based) with Gin integration
mathutilMath helpers: Clamp, Round, MinMax, Truncate
metricsMetrics helpers
migrationDatabase migration sources (filesystem, GORM migrator)
netutilPort availability and IP address helpers
nltimeNatural-language time expression parser
notificationNotification channel abstraction
opentelemetryOpenTelemetry helpers
parserASR and other parsing utilities
passkeyWebAuthn / Passkey server-side ceremony
passwordPassword hashing helpers
phonePhone number location lookup
pinyinChinese pinyin conversion
poolConnection pool utilities
qrcodeQR code encode/decode
queueCapacity scheduler and queue utilities
randomCryptographically secure random (numbers, strings, bytes)
responseAppError and unified response helpers
retryRetry framework with backoff strategies
schedulerDistributed task scheduler with locking
searchSearch engine abstraction
statsStatistics and archiving utilities
systemSystem info (disk cache, etc.)
timeutilTime formatting, parsing, and range helpers
totpTOTP / HOTP for 2FA (RFC 6238 / 4226)
tracingTracing attributes and helpers
validateInput validation helpers
videoutilVideo processing (ffmpeg command builders)

Quick Start

import "github.com/LingByte/ling-base/common"

// Environment variables (cached)
dbHost := common.GetEnv("DB_HOST")
port := common.GetEnvInt("DB_PORT", 3306)

// GORM database
db, err := common.InitDatabase(nil, "mysql", "user:pass@tcp(127.0.0.1:3306)/db")

// Content type lookup
ct := common.GetContentType(".json") // "application/json"

// Snowflake ID (via idgen)
id := common.NextSnowflakeUint()

On this page