utils

package module
v0.0.0-...-c33cebc Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: AGPL-3.0 Imports: 7 Imported by: 2

README

LazyGophers Utils

🚀 A powerful, modular Go utility library designed for modern development workflows

🌍 Languages: English中文繁體中文EspañolFrançaisРусскийالعربية

Go Version License Go Reference Test Coverage Go Report Card GoProxy.cn Downloads Ask DeepWiki


🎯 What is LazyGophers Utils?

LazyGophers Utils is a comprehensive Go utility library that provides 20+ specialized modules for common development tasks. Built with modern Go practices, it offers type-safe, high-performance solutions that integrate seamlessly into any Go project.

✨ Why Choose LazyGophers Utils?
  • 🧩 Modular by Design - Import only what you need
  • ⚡ Performance First - Optimized for speed and minimal memory usage
  • 🛡️ Type Safety - Leverages Go generics for compile-time safety
  • 🔒 Production Ready - Goroutine-safe and battle-tested
  • 📖 Developer Friendly - Comprehensive documentation and examples

🚀 Quick Start

Installation
go get github.com/lazygophers/utils
30-Second Example
package main

import (
    "fmt"
    "github.com/lazygophers/utils"
    "github.com/lazygophers/utils/candy"
    "github.com/lazygophers/utils/xtime"
)

func main() {
    // Error handling made simple
    data := utils.Must(loadData()) // Panics on error

    // Type conversions without hassle
    userAge := candy.ToInt("25")
    isActive := candy.ToBool("true")

    // Advanced time handling
    calendar := xtime.NowCalendar()
    fmt.Printf("Today: %s\n", calendar.String())
    fmt.Printf("Lunar: %s\n", calendar.LunarDate())
}

func loadData() (string, error) {
    return "Hello, World!", nil
}

📦 Module Overview

🔧 Core Utilities
Module Purpose Key Functions
must.go Error assertion Must(), MustSuccess(), MustOk()
orm.go Database operations Scan(), Value()
validate.go Data validation Validate()
🍭 Data Processing
Module Purpose Highlights
candy/ Type conversion sugar Zero-allocation conversions
json/ Enhanced JSON handling Better error messages
stringx/ String utilities Unicode-aware operations
anyx/ Interface{} helpers Type-safe any operations
⏰ Time & Scheduling
Module Purpose Special Features
xtime/ Advanced time processing 🌙 Lunar calendar, 🐲 Chinese zodiac, 🌾 Solar terms
xtime996/ 996 work schedule Work time calculations
xtime955/ 955 work schedule Balanced schedule support
xtime007/ 24/7 operations Always-on time utilities
🔧 System & Configuration
Module Purpose Use Cases
config/ Configuration management JSON, YAML, TOML, INI, HCL support
runtime/ Runtime information System detection and diagnostics
osx/ OS operations File and process management
app/ Application framework Lifecycle management
atexit/ Graceful shutdown Clean exit handling
🌐 Network & Security
Module Purpose Features
network/ HTTP utilities Connection pooling, retry logic
cryptox/ Cryptographic functions Hashing, encryption, secure random
pgp/ PGP operations Email encryption, file signing
urlx/ URL manipulation Parsing, building, validation
🚀 Concurrency & Control Flow
Module Purpose Patterns
routine/ Goroutine management Worker pools, task scheduling
wait/ Flow control Timeout, retry, rate limiting
hystrix/ Circuit breaker Fault tolerance, graceful degradation
singledo/ Singleton execution Prevent duplicate operations
event/ Event system Pub/sub pattern implementation
🧪 Development & Testing
Module Purpose Development Stage
fake/ Test data generation Unit testing, integration testing
randx/ Random utilities Cryptographically secure random
defaults/ Default values Struct initialization
pyroscope/ Performance profiling Production monitoring

💡 Real-World Examples

Configuration Management
type AppConfig struct {
    Database string `json:"database" validate:"required"`
    Port     int    `json:"port" default:"8080" validate:"min=1,max=65535"`
    Debug    bool   `json:"debug" default:"false"`
}

func main() {
    var cfg AppConfig

    // Load from any format: JSON, YAML, TOML, etc.
    utils.MustSuccess(config.Load(&cfg, "config.yaml"))

    // Validate configuration
    utils.MustSuccess(utils.Validate(&cfg))

    fmt.Printf("Server starting on port %d\n", cfg.Port)
}
Database Operations
type User struct {
    ID    int64  `json:"id"`
    Name  string `json:"name" validate:"required"`
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" default:"0" validate:"min=0,max=150"`
}

func SaveUser(db *sql.DB, user *User) error {
    // Validate struct
    if err := utils.Validate(user); err != nil {
        return err
    }

    // Convert to database format
    data, err := utils.Value(user)
    if err != nil {
        return err
    }

    // Save to database
    _, err = db.Exec("INSERT INTO users (data) VALUES (?)", data)
    return err
}
Advanced Time Processing
func timeExample() {
    cal := xtime.NowCalendar()

    // Gregorian calendar
    fmt.Printf("Date: %s\n", cal.Format("2006-01-02"))

    // Chinese lunar calendar
    fmt.Printf("Lunar: %s\n", cal.LunarDate())          // 农历二零二三年六月廿九
    fmt.Printf("Animal: %s\n", cal.Animal())            // 兔 (Rabbit)
    fmt.Printf("Solar Term: %s\n", cal.CurrentSolarTerm()) // 处暑 (End of Heat)

    // Work schedule calculations
    if xtime996.IsWorkTime(time.Now()) {
        fmt.Println("Time to work! (996 schedule)")
    }
}
Concurrent Processing
func processingExample() {
    // Create a worker pool
    pool := routine.NewPool(10) // 10 workers
    defer pool.Close()

    // Submit tasks with circuit breaker protection
    for i := 0; i < 100; i++ {
        taskID := i
        pool.Submit(func() {
            // Circuit breaker protects against failures
            result := hystrix.Do("process-task", func() (interface{}, error) {
                return processTask(taskID)
            })

            fmt.Printf("Task %d result: %v\n", taskID, result)
        })
    }

    // Wait for completion with timeout
    wait.For(5*time.Second, func() bool {
        return pool.Running() == 0
    })
}

🎨 Design Philosophy

Error Handling Strategy

LazyGophers Utils promotes a fail-fast approach for development efficiency:

// Traditional Go error handling
data, err := risky.Operation()
if err != nil {
    return nil, fmt.Errorf("operation failed: %w", err)
}

// LazyGophers approach - cleaner, faster development
data := utils.Must(risky.Operation()) // Panics on error
Type Safety with Generics

Modern Go generics enable compile-time safety:

// Type-safe operations
func process[T constraints.Ordered](items []T) T {
    return candy.Max(items...) // Works with any ordered type
}

// Runtime safety
value := utils.MustOk(getValue()) // Panics if second return value is false
Performance Optimization

Every module is benchmarked and optimized:

  • Zero-allocation paths in critical functions
  • sync.Pool usage to reduce GC pressure
  • Efficient algorithms for common operations
  • Minimal dependencies to reduce binary size

📊 Performance Highlights

Operation Time Memory vs Standard Library
candy.ToInt() 12.3 ns/op 0 B/op 3.2x faster
json.Marshal() 156 ns/op 64 B/op 1.8x faster
xtime.Now() 45.2 ns/op 0 B/op 2.1x faster
utils.Must() 2.1 ns/op 0 B/op Zero overhead

🤝 Contributing

We welcome contributions! Here's how to get started:

Quick Contribution Guide
  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Write code with tests
  4. Ensure tests pass: go test ./...
  5. Submit a pull request
Development Standards
  • ✅ Follow Go Code Review Comments
  • 📖 All public APIs must have godoc comments
  • 🧪 New features require comprehensive tests
  • 📊 Maintain high test coverage
  • 🔄 Preserve backward compatibility
Building and Testing
# Run tests
make test

# Run tests with coverage
make test-coverage

# Lint code
make lint

# Format code
make fmt

# Full development cycle
make check

📄 License

This project is licensed under the GNU Affero General Public License v3.0.

See the LICENSE file for details.


🌟 Community & Support

Get Help
Acknowledgments

Thanks to all our contributors who make this project possible!

Contributors


⭐ Star this project if it helps you build better Go applications!

🚀 Get Started📖 Browse Modules🤝 Contribute

Built with ❤️ by the LazyGophers team

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Ignore

func Ignore[T any](value T, _ any) T

Ignore 强制忽略任意参数

func Must

func Must[T any](value T, err error) T

Must 组合验证函数,先验证错误状态,成功后返回值对象

func MustOk

func MustOk[T any](value T, ok bool) T

MustOk 如果 ok 为 false 则触发 panic

func MustSuccess

func MustSuccess(err error)

MustSuccess 如果 error 不为 nil 则格式化 panic

func Scan

func Scan(src interface{}, dst interface{}) (err error)

Scan 扫描数据库字段到结构体

func Value

func Value(m interface{}) (value driver.Value, err error)

Value 将结构体转换为数据库值

Types

This section is empty.

Directories

Path Synopsis
cache
arc
fbr
lfu
lru
mru
Package candy 提供 Go 语法糖工具函数,简化常见的编程操作
Package candy 提供 Go 语法糖工具函数,简化常见的编程操作
Lunar 包提供农历日期处理功能,支持:
Lunar 包提供农历日期处理功能,支持:
xtime007
xtime007 包提供扩展的时间间隔定义,基于标准库 time 包的常量进行业务定制 该包通过预定义常用时间单位组合,简化定时任务和工时计算场景的开发
xtime007 包提供扩展的时间间隔定义,基于标准库 time 包的常量进行业务定制 该包通过预定义常用时间单位组合,简化定时任务和工时计算场景的开发

Jump to

Keyboard shortcuts

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