Skip to content

lazygophers/utils

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

LazyGophers Utils

πŸš€ A powerful, modular Go utility library designed for modern development workflows

🌍 Languages: English β€’ δΈ­ζ–‡ β€’ 繁體中文 β€’ EspaΓ±ol β€’ FranΓ§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

About

No description, website, or topics provided.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •  

Languages