Fabrica Util is a comprehensive utility library for the go-pantheon ecosystem, providing common functionality for all go-pantheon components. This library encapsulates reusable code patterns, algorithms, and helper functions to ensure consistency and avoid duplication in the game server microservices infrastructure.
For more information, please check out: deepwiki/go-pantheon/fabrica-util
go-pantheon is an out-of-the-box game server framework providing high-performance, highly available game server cluster solutions based on microservices architecture using go-kratos. Fabrica Util serves as the foundational utility library that supports the core components:
- Roma: Game core logic services
- Janus: Gateway service for client connection handling and request forwarding
- Lares: Account service for user authentication and account management
- Senate: Backend management service providing operational interfaces
- 🕒 Time Utilities: Advanced time handling with multi-language support, timezone management, and period calculations
- 🔄 Concurrency: Thread-safe synchronization primitives including delayers, futures, and goroutine management
- 🔐 Security: Comprehensive cryptographic utilities (AES-GCM, RSA, ECDH) for secure data transmission
- 🆔 ID Management: Distributed ID generation with zone-based encoding and HashID obfuscation
- 🎲 Randomization: Secure random number generation and string creation utilities
- 📊 Data Structures: High-performance implementations (Bloom filter, Bitmap, Consistent Hash)
- 🧠 Memory Management: Multi-pool memory management for optimized resource utilization
- 🔤 String Processing: Case conversion and text manipulation utilities
⚠️ Error Handling: Enhanced error handling with context and stack trace support
Advanced time handling with multi-language support:
- Configurable timezone and language support
- Time format conversion with locale-specific formatting
- Daily/weekly/monthly period calculations
- Time zone conversion utilities
Thread-safe synchronization primitives:
- Delayer: Time-based task scheduling with expiry management
- Future: Asynchronous computation results
- Closure: Thread-safe function execution wrappers
- Routines: Goroutine lifecycle management
Distributed ID management system:
- Zone-based ID combining for multi-region support
- HashID encoding/decoding for frontend display
- ID obfuscation for security purposes
Comprehensive cryptographic operations:
- AES: AES-GCM encryption/decryption with secure nonce generation
- RSA: Public/private key operations
- ECDH: Elliptic Curve Diffie-Hellman key exchange
- Certificate: X.509 certificate handling utilities
- Bloom Filter (
bloom/): Memory-efficient set membership testing - Bitmap (
bitmap/): Bit-level operations for compact data storage - Consistent Hash (
consistenthash/): Distributed hash ring for load balancing
- Random (
xrand/): Cryptographically secure random number generation - Compression (
compress/): Data compression utilities - CamelCase (
camelcase/): String case conversion utilities - Multi-pool (
multipool/): Memory pool management - Errors (
errors/): Enhanced error handling with context
| Technology/Component | Purpose | Version |
|---|---|---|
| Go | Primary development language | 1.24+ |
| crypto | Cryptographic operations | v0.39.0 |
| go-redis | Redis client for distributed operations | v9.10.0 |
| PostgreSQL Driver | Database connectivity | v5.7.5 |
| MongoDB Driver | NoSQL database operations | v2.2.2 |
| HashIDs | ID obfuscation library | v2.0.1 |
| Murmur3 | Fast hash algorithm | v1.1.0 |
- Go 1.24+
go get github.com/go-pantheon/fabrica-utilmake initmake testpackage main
import (
"fmt"
"time"
"github.com/go-pantheon/fabrica-util/xtime"
)
func main() {
// Initialize with configuration
err := xtime.Init(xtime.Config{
Language: "en",
Timezone: "Asia/Shanghai",
})
if err != nil {
panic(err)
}
// Format current time
fmt.Println(xtime.Format(time.Now()))
// Calculate next daily reset time (5 AM reset)
nextReset := xtime.NextDailyTime(time.Now(), 5*time.Hour)
fmt.Println("Next daily reset:", nextReset)
// Get start of current week
weekStart := xtime.StartOfWeek(time.Now())
fmt.Println("Week starts at:", weekStart)
}package main
import (
"fmt"
"github.com/go-pantheon/fabrica-util/security/aes"
)
func main() {
// Create AES cipher with 32-byte key
key := []byte("0123456789abcdef0123456789abcdef")
cipher, err := aes.NewAESCipher(key)
if err != nil {
panic(err)
}
data := []byte("sensitive game data")
// Encrypt data
encrypted, err := cipher.Encrypt(data)
if err != nil {
panic(err)
}
// Decrypt data
decrypted, err := cipher.Decrypt(encrypted)
if err != nil {
panic(err)
}
fmt.Printf("Original: %s\n", data)
fmt.Printf("Decrypted: %s\n", decrypted)
}package main
import (
"fmt"
"github.com/go-pantheon/fabrica-util/xid"
)
func main() {
// Combine zone ID with zone number
playerID := int64(12345)
zoneNum := uint8(3)
combinedID := xid.CombineZoneID(playerID, zoneNum)
// Encode ID for frontend display
encodedID, err := xid.EncodeID(combinedID)
if err != nil {
panic(err)
}
fmt.Printf("Encoded ID: %s\n", encodedID)
// Decode ID
decodedID, err := xid.DecodeID(encodedID)
if err != nil {
panic(err)
}
// Split ID back to original components
originalPlayerID, originalZone := xid.SplitID(decodedID)
fmt.Printf("Player ID: %d, Zone: %d\n", originalPlayerID, originalZone)
}package main
import (
"fmt"
"time"
"github.com/go-pantheon/fabrica-util/xsync"
)
func main() {
// Create a delayer
delayer := xsync.NewDelayer()
defer delayer.Close()
// Set expiry time (5 seconds from now)
expiryTime := time.Now().Add(5 * time.Second)
delayer.SetExpiryTime(expiryTime)
fmt.Println("Waiting for delayer to expire...")
// Wait for expiry
select {
case <-delayer.Wait():
fmt.Println("Delayer expired!")
case <-time.After(10 * time.Second):
fmt.Println("Timeout waiting for delayer")
}
}.
├── xtime/ # Time utilities with locale support
├── xsync/ # Synchronization primitives
│ ├── delayer.go # Time-based task scheduling
│ ├── future.go # Asynchronous computation
│ ├── closure.go # Thread-safe function wrappers
│ └── routines.go # Goroutine management
├── xrand/ # Secure random number generation
├── xid/ # ID generation and obfuscation
├── security/ # Cryptographic operations
│ ├── aes/ # AES-GCM encryption
│ ├── rsa/ # RSA encryption
│ ├── ecdh/ # Elliptic Curve Diffie-Hellman
│ └── certificate/ # X.509 certificate utilities
├── consistenthash/ # Consistent hash implementation
├── multipool/ # Memory pool management
├── errors/ # Enhanced error handling
├── bloom/ # Bloom filter implementation
├── compress/ # Data compression utilities
├── bitmap/ # Bitmap data structure
└── camelcase/ # String case conversion
Fabrica Util is designed to be imported by other go-pantheon components:
import (
// Security utilities for token generation in Lares
"github.com/go-pantheon/fabrica-util/security/aes"
// Time utilities for game logic in Roma
"github.com/go-pantheon/fabrica-util/xtime"
// Synchronization utilities for connection handling in Janus
"github.com/go-pantheon/fabrica-util/xsync"
// ID management for distributed player identification
"github.com/go-pantheon/fabrica-util/xid"
)The project enforces license compliance for all dependencies. We only allow the following licenses:
- MIT
- Apache-2.0
- BSD-2-Clause
- BSD-3-Clause
- ISC
- MPL-2.0
License checks are performed:
- Automatically in CI/CD pipelines
- Locally via pre-commit hooks
- Manually using
make license-check
Run the complete test suite:
# Run all tests with coverage
make test
# Run linting
make lint
# Run go vet
make vetWhen adding new utility functions:
- Create a new package or add to an existing one based on functionality
- Implement the utility functions with proper error handling
- Write comprehensive unit tests with edge cases covered
- Document usage with clear examples
- Ensure thread safety where applicable
- Run tests:
make test - Update documentation if needed
- Fork this repository
- Create a feature branch from
main - Implement changes with comprehensive tests
- Ensure all tests pass and linting is clean
- Update documentation for any API changes
- Submit a Pull Request with clear description
- Memory Pools: Use
multipoolfor high-frequency object allocation - Cryptography: AES-GCM operations are optimized for throughput
- ID Generation: HashID encoding is cached for repeated operations
- Time Operations: Timezone loading is cached and reused
- Synchronization: All sync primitives are designed for low contention
This project is licensed under the terms specified in the LICENSE file.