utils

package module
v0.0.0-...-5b16191 Latest Latest
Warning

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

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

README

LazyGophers Utils

🚀 A feature-rich, high-performance Go utility library that makes Go development more efficient

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

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

📋 Table of Contents

💡 Project Overview

LazyGophers Utils is a comprehensive, high-performance Go utility library that provides 20+ professional modules covering various needs in daily development. It adopts a modular design for on-demand imports with zero dependency conflicts.

Design Philosophy: Simple, Efficient, Reliable

✨ Core Features

Feature Description Advantage
🧩 Modular Design 20+ independent modules Import on demand, reduce size
High Performance Benchmark tested Microsecond response, memory friendly
🛡️ Type Safe Full use of generics Compile-time error checking
🔒 Concurrency Safe Goroutine-friendly design Production ready
📚 Well Documented 95%+ documentation coverage Easy to learn and use
🧪 Well Tested 98%+ test coverage Quality assurance

🚀 Quick Start

Installation
go get github.com/lazygophers/utils
Basic Usage
package main

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

func main() {
    // Error handling
    value := utils.Must(getValue())
    
    // Type conversion
    age := candy.ToInt("25")
    
    // Time processing
    cal := xtime.NowCalendar()
    fmt.Println(cal.String()) // 2023年08月15日 六月廿九 兔年 处暑
}

📖 Documentation

📁 Module Documentation
📋 Quick Reference
🌍 Multi-language Documentation

🔧 Core Modules

Error Handling (must.go)
// Assert operation success, panic on failure
value := utils.Must(getValue())

// Verify no error
utils.MustSuccess(doSomething())

// Verify boolean status
result := utils.MustOk(checkCondition())
Database Operations (orm.go)
type User struct {
    Name string `json:"name"`
    Age  int    `json:"age" default:"18"`
}

// Scan database data to struct
err := utils.Scan(dbData, &user)

// Convert struct to database value
value, err := utils.Value(user)
Data Validation (validate.go)
type Config struct {
    Email string `validate:"required,email"`
    Port  int    `validate:"min=1,max=65535"`
}

// Quick validation
err := utils.Validate(&config)

📦 Feature Modules

🍭 Data Processing Modules
Module Function Core API
candy Type conversion syntactic sugar ToInt(), ToString(), ToBool()
json Enhanced JSON processing Marshal(), Unmarshal(), Pretty()
stringx String processing IsEmpty(), Contains(), Split()
anyx Any type tools IsNil(), Type(), Convert()
⏰ Time Processing Modules
Module Function Features
xtime Enhanced time processing Lunar calendar, solar terms, zodiac
xtime996 996 work schedule constants Work time calculation
xtime955 955 work schedule constants Work time calculation
xtime007 007 work schedule constants 24/7 time

xtime Special Features:

  • 🗓️ Unified calendar interface (Gregorian + Lunar)
  • 🌙 Accurate lunar conversion and solar term calculation
  • 🐲 Complete Heavenly Stems and Earthly Branches system
  • 🏮 Automatic traditional festival detection
cal := xtime.NowCalendar()
fmt.Println(cal.LunarDate())     // 农历二零二三年六月廿九
fmt.Println(cal.Animal())        // 兔
fmt.Println(cal.CurrentSolarTerm()) // 处暑
🔧 System Tool Modules
Module Function Purpose
config Configuration management Multi-format config file reading
runtime Runtime information System information retrieval
osx OS enhancement File and process operations
app Application framework Application lifecycle management
atexit Exit hooks Graceful shutdown handling
🌐 Network & Security Modules
Module Function Use Cases
network Network operations HTTP client, connection pool
cryptox Cryptographic tools Hash, encryption, decryption
pgp PGP encryption Email encryption, file signing
urlx URL processing URL parsing, building
🚀 Concurrency & Control Modules
Module Function Design Pattern
routine Goroutine management Goroutine pool, task scheduling
wait Wait control Timeout, retry, rate limiting
hystrix Circuit breaker Fault tolerance, degradation
singledo Singleton pattern Prevent duplicate execution
event Event-driven Publish-subscribe pattern
🧪 Development & Testing Modules
Module Function Development Stage
fake Fake data generation Test data generation
unit Testing assistance Unit testing tools
pyroscope Performance analysis Production monitoring
defaults Default values Configuration initialization
randx Random numbers Secure random generation

🎯 Usage Examples

Complete Application Example
package main

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

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

func main() {
    // 1. Load configuration
    var cfg AppConfig
    utils.MustSuccess(config.Load(&cfg, "config.json"))
    
    // 2. Validate configuration
    utils.MustSuccess(utils.Validate(&cfg))
    
    // 3. Type conversion
    portStr := candy.ToString(cfg.Port)
    
    // 4. Time processing
    cal := xtime.NowCalendar()
    log.Printf("Application started: %s", cal.String())
    
    // 5. Start server
    startServer(cfg)
}
Error Handling Best Practices
// ✅ Recommended: Use Must series functions
func processData() string {
    data := utils.Must(loadData())        // Panic on load failure
    utils.MustSuccess(validateData(data)) // Panic on validation failure
    return utils.MustOk(transformData(data)) // Panic on transform failure
}

// ✅ Recommended: Batch error handling
func batchProcess() error {
    return utils.MustSuccess(
        doStep1(),
        doStep2(),
        doStep3(),
    )
}
Database Operation Example
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 data
    if err := utils.Validate(user); err != nil {
        return err
    }
    
    // Convert to database value
    data, err := utils.Value(user)
    if err != nil {
        return err
    }
    
    // Save to database
    _, err = db.Exec("INSERT INTO users (data) VALUES (?)", data)
    return err
}

func GetUser(db *sql.DB, id int64) (*User, error) {
    var data []byte
    err := db.QueryRow("SELECT data FROM users WHERE id = ?", id).Scan(&data)
    if err != nil {
        return nil, err
    }
    
    var user User
    err = utils.Scan(data, &user)
    return &user, err
}

📊 Performance Data

Benchmark Results
Operation Time Memory Allocation 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
Performance Characteristics
  • Microsecond Response: Core operations complete in microseconds
  • 🧠 Memory Friendly: Use sync.Pool to reduce GC pressure
  • 🔄 Zero Allocation: Avoid memory allocation in critical paths
  • 🚀 Concurrency Optimized: Optimized for high-concurrency scenarios

📈 Detailed Performance Report: Performance Documentation

🤝 Contributing

We welcome contributions of all kinds!

Contribution Process
  1. 🍴 Fork the project
  2. 🌿 Create a feature branch: git checkout -b feature/amazing-feature
  3. 📝 Write code and tests
  4. 🧪 Ensure tests pass: go test ./...
  5. 📤 Submit PR
Development Standards
  • ✅ Follow Go Code Review Comments
  • 📖 All public APIs must have godoc comments
  • 🧪 New features must include test cases
  • 📊 Maintain test coverage > 80%
  • 🔄 Maintain backward compatibility

📋 Detailed Guidelines: Contributing Guide

📄 License

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

See the LICENSE file for details.

🌟 Community Support

Getting Help
Project Statistics
Metric Value Description
📦 Module Count 20+ Cover various common functions
🧪 Test Coverage 85%+ High-quality code assurance
📝 Documentation Completeness 95%+ Detailed usage instructions
⚡ Performance Grade A+ Benchmark tested optimization
🌟 GitHub Stars GitHub stars Community recognition
Acknowledgments

Thanks to all contributors for their hard work!

Contributors


If this project helps you, please give us a ⭐ Star!

🚀 Get Started📖 View Documentation🤝 Join Community

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 开发中的常见操作
Package human 提供人类友好的数据格式化功能,支持多语言和多种数据类型
Package human 提供人类友好的数据格式化功能,支持多语言和多种数据类型
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