๐ ๏ธ Go Utils

A comprehensive collection of Go utility libraries and self-developed components with simple and elegant encapsulations.
This package continuously adopts the latest Go versions and cutting-edge technologies to maintain the most modern and advanced features. We prioritize performance optimization while keeping everything simple and reliable.
ไธญๆๆๆกฃ | English
๐ Table of Contents
๐ Installation
go get github.com/bizvip/go-utils
๐ฏ Quick Start
package main
import (
"fmt"
"github.com/bizvip/go-utils/base/num"
"github.com/bizvip/go-utils/base/str"
)
func main() {
// Mathematical expression calculation
result, _ := num.Calc("(2 + 3) * 4")
fmt.Println("Result:", result) // Result: 20
// String utilities
encoded := str.Base62Encode(12345)
fmt.Println("Encoded:", encoded)
}
๐ฆ Package Overview
๐ข Base Utilities
| Package |
Description |
Key Features |
| base/num |
Numerical operations and calculations |
Expression calculator with AST parsing, decimal handling, Sqids hash ID encoding |
| base/str |
String manipulation utilities |
Base26/Base62 encoding, hash calculations (MD5/SHA256/SHA3), Unicode operations |
| base/str/base26 |
Base26 encoding |
Numeric/string to base26 conversions, validation |
| base/str/base62 |
Base62 encoding |
SHA256 <-> Base62 conversions |
| base/crypto |
Cryptographic operations |
AES-GCM encryption/decryption with PBKDF2 key derivation |
| base/blake3hash |
BLAKE3 hashing |
Stream/file hashing helpers |
| base/dt |
Date and time utilities |
Timezone offset calculations, timestamp manipulation, time comparisons |
| base/pwd |
Password utilities |
Argon2 hashing, security password validation with pattern checks |
| base/collections |
Generic collections (Go 1.24+) |
Filter, Map, Reduce, GroupBy, Chunk with type safety |
| base/validator |
Validation framework |
Generic validators, email/phone/ID card validation |
| base/id/sqids |
ID generation |
Sqids library integration for hash IDs |
| base/snowflake |
Snowflake IDs |
Yitter ID Generator, custom base time support |
| base/rnd |
Random generation |
Cryptographically secure random strings, UUID generation |
| base/json |
JSON utilities |
goccy/go-json integration, pretty formatting |
| base/reflects |
Reflection helpers |
Struct merge and Struct-to-map conversion |
| base/htm |
HTML utilities |
HTML compression and minification |
๐ Network & APIs
| Package |
Description |
Key Features |
| network/google |
Google services integration |
Translate API with batch processing via RapidAPI |
| network/exchange/binance |
Binance exchange API |
Market data retrieval with automatic fallback |
| network/exchange/okx |
OKX exchange API |
Fiat/crypto exchange rates |
| network/hcaptcha |
hCaptcha verification |
Server-side token verification |
| network/httputils |
HTTP utilities |
Image download with custom headers, path sanitization |
| network/ip |
IP utilities |
Local/public IP, GeoIP, client info |
| network/ua |
User-Agent parser |
Parses UA strings into device/browser info |
โ๏ธ Cloud Services
| Package |
Description |
Key Features |
| cloudservice/wasabi |
S3-compatible storage |
Wasabi cloud storage interface |
๐ผ๏ธ Image
| Package |
Description |
Key Features |
| img |
Image utilities |
Base64 conversion, resize, image info (optional libvips) |
๐ฏ I18n & Localization
| Package |
Description |
Key Features |
| i18n/goi18n |
i18n helpers |
go-i18n integration helpers |
| i18n/opencc |
Chinese conversion |
OpenCC wrapper utilities |
๐ Constants
| Package |
Description |
Key Features |
| consts/cryptocurrency |
Crypto constants |
Coin/network/token constants, explorers |
| consts/currencycode |
Currency codes |
Fiat currency code constants |
๐งฉ Patterns & Concurrency
| Package |
Description |
Key Features |
| lock |
Adaptive lock |
Sharded lock with cleanup |
| oo/singleton |
Singleton helpers |
Lazy initialization, per-key singleton |
๐งฐ Infrastructure & Models
| Package |
Description |
Key Features |
| etcd |
etcd client wrapper |
KV ops, leases, locks, watch |
| ex |
Error model |
Structured error type with metadata |
๐ ๏ธ System & OS
| Package |
Description |
Key Features |
| os |
Byte size helpers |
ByteSize conversions and formatting |
| os/console |
Console utilities |
Colored terminal output, progress bars, formatted display |
| os/em |
Embed helpers |
Read embedded files and list directories |
| os/fs |
File system operations |
Cross-platform file handling (Darwin/Linux), hash calculations |
| os/fsn |
File watch |
fsnotify-based directory watcher |
| os/io/logger |
Logging |
Zerolog-based logger with DI and rotation |
โ๏ธ Configuration
| Package |
Description |
Key Features |
| conf |
Generic configuration management |
Go 1.24+ generics, Viper integration, file watching |
๐ Complete Function Directory
base/blake3hash
Must โ base/blake3hash/blake3hash.go
SumBytes โ base/blake3hash/blake3hash.go
SumFile โ base/blake3hash/blake3hash.go
SumReader โ base/blake3hash/blake3hash.go
base/crypto
AesDecrypt โ base/crypto/aes.go
AesEncrypt โ base/crypto/aes.go
base/dt
AdjustMilliTimestamp โ base/dt/datetime.go
AdjustMilliTimestampByStr โ base/dt/datetime.go
CompareTimeStrings โ base/dt/datetime.go
ConvertStrMillisToTime โ base/dt/datetime.go
GetMicroTimestampStr โ base/dt/datetime.go
GetMilliTimestampStr โ base/dt/datetime.go
GetNanoTimestampStr โ base/dt/datetime.go
GetTimezoneOffsetByMillis โ base/dt/datetime.go
SetTimezone โ base/dt/datetime.go
TimeDifference โ base/dt/datetime.go
base/htm
Compress โ base/htm/htm.go
base/id/sqids
ToAlpha โ base/id/sqids/sqids.go
ToInt โ base/id/sqids/sqids.go
base/json
PrettyFormat โ base/json/goccy_json.go
ToJsonWithNoErr โ base/json/goccy_json.go
base/num
Calc โ base/num/num.go
Calculator.Evaluate โ base/num/calculator.go
CheckNumStrInRange โ base/num/num.go
DecimalFormatBanker โ base/num/num.go
Evaluate โ base/num/calculator.go
EvaluateToString โ base/num/calculator.go
FormatNumStrToDecimalAndShift โ base/num/num.go
GetMaxNum โ base/num/num.go
HashIdToInt64 โ base/num/num.go
Int64ToHashId โ base/num/num.go
MergeToDecimal โ base/num/num.go
NewCalculator โ base/num/calculator.go
StrToDecimalTruncate โ base/num/num.go
ValidateSecPwd โ base/num/num.go
base/pwd
GenSalt โ base/pwd/pwd.go
IsCorrect โ base/pwd/pwd.go
SplitHash โ base/pwd/pwd.go
ToHash โ base/pwd/pwd.go
ToHashWithConfig โ base/pwd/pwd.go
ValidateSHA256 โ base/pwd/validate.go
ValidateSixNumberAsPwd โ base/pwd/validate.go
base/reflects
MergeStructData โ base/reflects/reflects.go
base/rnd
GenNumberInRange โ base/rnd/rnd.go
GenRandomAlphaNumeric โ base/rnd/rnd.go
RandNumStr โ base/rnd/rnd.go
RandNumStrNonSafe โ base/rnd/rnd.go
RandomCnName โ base/rnd/cn_usr.go
UUID โ base/rnd/rnd.go
base/snowflake
NewShortIdGenerator โ base/snowflake/short_version.go
ShortIdGenerator.BatchNext โ base/snowflake/short_version.go
ShortIdGenerator.Decompose โ base/snowflake/short_version.go
ShortIdGenerator.NextID โ base/snowflake/short_version.go
base/str
CalcHash โ base/str/str.go
FilterEmptyChar โ base/str/str.go
GenFixedStrWithSeed โ base/str/str.go
GenSha1 โ base/str/str.go
GenSlug โ base/str/str.go
GetDirNameFromSnowflakeID โ base/str/str.go
Md5 โ base/str/str.go
PadCnSpaceChar โ base/str/str.go
RegexpMatch โ base/str/str.go
Sha256 โ base/str/str.go
ToInt64 โ base/str/str.go
ToPrettyJson โ base/str/str.go
ToUint32 โ base/str/str.go
UnicodeLength โ base/str/str.go
UniqueStrings โ base/str/str.go
base/str/base26
Int64ToAlpha โ base/str/base26/base26.go
IsValidBase26 โ base/str/base26/base26.go
StrNumToAlpha โ base/str/base26/base26.go
ToNum โ base/str/base26/base26.go
Uint64ToAlpha โ base/str/base26/base26.go
base/str/base62
Base62ToSHA256 โ base/str/base62/base62.go
SHA256ToBase62 โ base/str/base62/base62.go
base/validator
InRule[T].Validate โ base/validator/validator.go
IsAlphaNum โ base/validator/str.go
IsDomainResolvable โ base/validator/email.go
IsEmailAddrValidWithDomain โ base/validator/email.go
IsLengthBetween โ base/validator/str.go
IsMd5 โ base/validator/str.go
IsValidDomain โ base/validator/email.go
IsValidEmailFormat โ base/validator/email.go
NewRegexRule โ base/validator/validator.go
RangeRule[T].Validate โ base/validator/validator.go
RegexRule.Validate โ base/validator/validator.go
RequiredRule[T].Validate โ base/validator/validator.go
StringLengthRule.Validate โ base/validator/validator.go
ValidateEmail โ base/validator/validator.go
ValidateIDCard โ base/validator/validator.go
ValidatePassword โ base/validator/validator.go
ValidatePhone โ base/validator/validator.go
ValidationError.Error โ base/validator/validator.go
Validator[T].AddRule โ base/validator/validator.go
Validator[T].Validate โ base/validator/validator.go
cloudservice/wasabi
NewWasabiHandler โ cloudservice/wasabi/wasabi.go
s3Conf.DelFile โ cloudservice/wasabi/storage_interface.go
s3Conf.GetAccessKey โ cloudservice/wasabi/storage_interface.go
s3Conf.GetAllBuckets โ cloudservice/wasabi/storage_interface.go
s3Conf.GetAllFilesFromBucket โ cloudservice/wasabi/storage_interface.go
s3Conf.GetBucketName โ cloudservice/wasabi/storage_interface.go
s3Conf.GetEndpoint โ cloudservice/wasabi/storage_interface.go
s3Conf.GetFile โ cloudservice/wasabi/storage_interface.go
s3Conf.GetRegion โ cloudservice/wasabi/storage_interface.go
s3Conf.GetSecretKey โ cloudservice/wasabi/storage_interface.go
s3Conf.PutFile โ cloudservice/wasabi/storage_interface.go
conf
AppConfig.SetDefaults โ conf/example.go
Manager[T].GetConfig โ conf/config.go
Manager[T].LoadFile โ conf/config.go
Manager[T].UpdateConfig โ conf/config.go
cryptocoin
DetectAddress โ cryptocoin/validate.go
IsValidBEP20Address โ cryptocoin/validate.go
IsValidBTCAddress โ cryptocoin/validate.go
IsValidERC20Address โ cryptocoin/validate.go
IsValidEVMAddress โ cryptocoin/validate.go
IsValidTONAddress โ cryptocoin/validate.go
IsValidTRC20Address โ cryptocoin/validate.go
ParseTONRaw โ cryptocoin/validate.go
etcd
Client.AcquireLock โ etcd/client.go
Client.Close โ etcd/client.go
Client.Connect โ etcd/client.go
Client.CreateLease โ etcd/client.go
Client.Get โ etcd/client.go
Client.KeepAliveLease โ etcd/client.go
Client.ListMembers โ etcd/client.go
Client.Put โ etcd/client.go
Client.RegisterService โ etcd/client.go
Client.ReleaseLock โ etcd/client.go
Client.Txn โ etcd/client.go
Client.Watch โ etcd/client.go
NewClient โ etcd/client.go
ex
Error.Error โ ex/ex_model.go
Error.MarshalZerologObject โ ex/ex_model.go
Error.SetMessage โ ex/ex_model.go
Error.SetMeta โ ex/ex_model.go
Error.String โ ex/ex_model.go
i18n/goi18n
I18nManager.GetTemplateLangMap โ i18n/goi18n/go_i18n.go
I18nManager.Translate โ i18n/goi18n/go_i18n.go
NewI18nManager โ i18n/goi18n/go_i18n.go
i18n/opencc
Convert โ i18n/opencc/opencc.go
SimpToTW โ i18n/opencc/opencc.go
SimpToTrad โ i18n/opencc/opencc.go
TWToS โ i18n/opencc/opencc.go
TradToSimp โ i18n/opencc/opencc.go
WarmUp โ i18n/opencc/opencc.go
img
Base64ToFile โ img/img_toolkit.go
GetImageInfo โ img/image_info.go, img/image_info_vips.go
ImageToBase64 โ img/img_toolkit.go
ResizeImage โ img/img_toolkit.go
lock
AdaptiveLock.GetActiveLockCount โ lock/lock.go
AdaptiveLock.IsShardMode โ lock/lock.go
AdaptiveLock.Lock โ lock/lock.go
AdaptiveLock.Unlock โ lock/lock.go
SetLockerAutoCleanup โ lock/lock.go
network/exchange/binance
GetApi โ network/exchange/binance/base.go
MarketService.GetAggTrades โ network/exchange/binance/market.go
MarketService.GetAvgPrice โ network/exchange/binance/market.go
MarketService.GetDepth โ network/exchange/binance/market.go
MarketService.GetExchangeInfo โ network/exchange/binance/market.go
MarketService.GetHistoricalTrades โ network/exchange/binance/market.go
MarketService.GetKlines โ network/exchange/binance/market.go
MarketService.GetPing โ network/exchange/binance/market.go
MarketService.GetServerTime โ network/exchange/binance/market.go
MarketService.GetTicker โ network/exchange/binance/market.go
MarketService.GetTicker24Hr โ network/exchange/binance/market.go
MarketService.GetTickerBookTicker โ network/exchange/binance/market.go
MarketService.GetTickerPrice โ network/exchange/binance/market.go
MarketService.GetTickerTradingDay โ network/exchange/binance/market.go
MarketService.GetTrades โ network/exchange/binance/market.go
MarketService.GetUIKlines โ network/exchange/binance/market.go
NewMarketService โ network/exchange/binance/market.go
network/exchange/okx
NewOkxExchangeService โ network/exchange/okx/okx.go
OKX.GetTop10Exchanges โ network/exchange/okx/okx.go
OKX.GetUsdtCnyExchangeList โ network/exchange/okx/okx.go
OKX.GetUsdtCnyRateOnly โ network/exchange/okx/okx.go
network/google
NewTranslationService โ network/google/google_translate.go
TranslationService.GoogleDetectLang โ network/google/google_translate.go
TranslationService.GoogleTranslateToCN โ network/google/google_translate.go
TranslationService.GoogleTranslateToEn โ network/google/google_translate.go
network/hcaptcha
NewHCaptchaVerifier โ network/hcaptcha/captcha.go
Verifier.Verify โ network/hcaptcha/captcha.go
network/httputils
DownImage โ network/httputils/download.go
network/ip
GetClientIP โ network/ip/ip.go
GetFullClientInfo โ network/ip/ip.go
GetGeoIPInfo โ network/ip/ip.go
GetLocalPrivateIP โ network/ip/ip.go
GetLocalPublicIP โ network/ip/ip.go
GetMyGeoIPInfo โ network/ip/ip.go
IsPrivateIP โ network/ip/ip.go
IsValidPublicIP โ network/ip/ip.go
ToUniqueStr โ network/ip/ip.go
network/ua
Parse โ network/ua/ua.go
oo/singleton
PerKey[K, V].Delete โ oo/singleton/singleton.go
PerKey[K, V].Get โ oo/singleton/singleton.go
PerKey[K, V].Has โ oo/singleton/singleton.go
PerKey[K, V].Range โ oo/singleton/singleton.go
os
ByteSize.String โ os/bytesize.go
ByteSize.ToGB โ os/bytesize.go
ByteSize.ToKB โ os/bytesize.go
ByteSize.ToMB โ os/bytesize.go
os/console
C.Black โ os/console/color.go
C.BlackBold โ os/console/color.go
C.Blue โ os/console/color.go
C.BlueBold โ os/console/color.go
C.Bluef โ os/console/color.go
C.Box โ os/console/color.go
C.Clear โ os/console/color.go
C.Cyan โ os/console/color.go
C.CyanBold โ os/console/color.go
C.Cyanf โ os/console/color.go
C.DashedLine โ os/console/color.go
C.DoubleLine โ os/console/color.go
C.Error โ os/console/color.go
C.Gray โ os/console/color.go
C.GrayBold โ os/console/color.go
C.Grayf โ os/console/color.go
C.Green โ os/console/color.go
C.GreenBold โ os/console/color.go
C.Greenf โ os/console/color.go
C.Info โ os/console/color.go
C.Italic โ os/console/color.go
C.KeyValue โ os/console/color.go
C.Line โ os/console/color.go
C.List โ os/console/color.go
C.Magenta โ os/console/color.go
C.MagentaBold โ os/console/color.go
C.Magentaf โ os/console/color.go
C.NewLine โ os/console/color.go
C.NumberedList โ os/console/color.go
C.Print โ os/console/color.go
C.Printf โ os/console/color.go
C.Println โ os/console/color.go
C.Progress โ os/console/color.go
C.Red โ os/console/color.go
C.RedBold โ os/console/color.go
C.Redf โ os/console/color.go
C.Section โ os/console/color.go
C.Spinner โ os/console/color.go
C.Success โ os/console/color.go
C.Title โ os/console/color.go
C.Underline โ os/console/color.go
C.Warning โ os/console/color.go
C.White โ os/console/color.go
C.WhiteBold โ os/console/color.go
C.Whitef โ os/console/color.go
C.WithWriter โ os/console/color.go
C.Yellow โ os/console/color.go
C.YellowBold โ os/console/color.go
C.Yellowf โ os/console/color.go
Console โ os/console/color.go
ConsoleErr โ os/console/color.go
os/em
GetFileByPath โ os/em/embed.go
GetFileList โ os/em/embed.go
os/fs
ComputeFileSHA256 โ os/fs/file_darwin.go, os/fs/file_linux.go
CreateDir โ os/fs/file_darwin.go, os/fs/file_linux.go
CreateDirIfNotExist โ os/fs/file_darwin.go, os/fs/file_linux.go
Delete โ os/fs/file_darwin.go, os/fs/file_linux.go
DetectFileType โ os/fs/file_darwin.go, os/fs/file_linux.go
GetAllFilesByExt โ os/fs/file_darwin.go, os/fs/file_linux.go
GetBigFileMd5 โ os/fs/file_darwin.go, os/fs/file_linux.go
GetCurExeDir โ os/fs/file_darwin.go, os/fs/file_linux.go
GetFileCreationTime โ os/fs/file_darwin.go, os/fs/file_linux.go
GetFileMd5 โ os/fs/file_linux.go
GetFileMd5Stream โ os/fs/file_linux.go
GetFileNameMd5 โ os/fs/file_darwin.go, os/fs/file_linux.go
GetSmallFileMd5 โ os/fs/file_darwin.go
IsDirAndHasFiles โ os/fs/file_darwin.go, os/fs/file_linux.go
IsFile โ os/fs/file_darwin.go, os/fs/file_linux.go
StartsWithDot โ os/fs/file_darwin.go, os/fs/file_linux.go
os/fsn
NewFsnWatcher โ os/fsn/fw_fsnotify.go
StartWatcher โ os/fsn/fw_fsnotify.go
Watcher.AddDirRecursive โ os/fsn/fw_fsnotify.go
Watcher.Close โ os/fsn/fw_fsnotify.go
Watcher.Start โ os/fsn/fw_fsnotify.go
os/io/logger
DefaultConfig โ os/io/logger/logger.go
Logger.Debug โ os/io/logger/logger.go
Logger.Debugf โ os/io/logger/logger.go
Logger.Error โ os/io/logger/logger.go
Logger.Errorf โ os/io/logger/logger.go
Logger.Fatal โ os/io/logger/logger.go
Logger.Fatalf โ os/io/logger/logger.go
Logger.Info โ os/io/logger/logger.go
Logger.Infof โ os/io/logger/logger.go
Logger.Panic โ os/io/logger/logger.go
Logger.Panicf โ os/io/logger/logger.go
Logger.Warn โ os/io/logger/logger.go
Logger.Warnf โ os/io/logger/logger.go
Logger.With โ os/io/logger/logger.go
Logger.WithFields โ os/io/logger/logger.go
LoggerMiddleware โ os/io/logger/example.go
Manager.GetLogger โ os/io/logger/logger.go
Manager.GetModuleLogger โ os/io/logger/logger.go
Manager.GetServiceLogger โ os/io/logger/logger.go
NewManager โ os/io/logger/logger.go
NewUserService โ os/io/logger/example.go
UserService.CreateUser โ os/io/logger/example.go
โจ Features
๐งฎ Advanced Calculator
// Supports complex mathematical expressions
result, _ := num.Calc("2 + 3 ร (4 รท 2)")
fmt.Println(result) // Output: 8
๐ Secure Password Validation
// Validates security passwords with custom rules
err := num.ValidateSecPwd("123456")
if err != nil {
fmt.Println("Invalid password:", err)
}
๐ Google Translate Integration
// Batch translation with Google Translate API
translations, _ := google.BatchTranslate(texts, "en", "zh")
๐ฑ Cryptocurrency Support
// Validate cryptocurrency addresses
isValid := cryptocoin.ValidateBTCAddress("1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa")
๐จ Console Styling
// Colorized console output
console.PrintSuccess("Operation completed successfully!")
console.PrintError("An error occurred!")
๐งช Testing
We maintain comprehensive test coverage for all packages:
# Run all tests with formatting
make test
# Run tests with coverage
make test-coverage
# Run benchmarks
make bench
# Full CI pipeline
make ci
Test Structure
tests/
โโโ base/
โ โโโ num/
โ โโโ calculator_test.go
โ โโโ num_test.go
โโโ [other packages]/
๐๏ธ Project Structure
go-utils/
โโโ base/ # Core utilities
โ โโโ crypto/ # Cryptographic functions
โ โโโ dt/ # Date/time utilities
โ โโโ num/ # Numerical operations
โ โโโ str/ # String manipulation
โ โโโ ...
โโโ network/ # Network-related packages
โ โโโ google/ # Google APIs
โ โโโ exchange/ # Crypto exchanges
โ โโโ ...
โโโ cloudservice/ # Cloud service integrations
โโโ tests/ # Centralized test files
โโโ Makefile # Build automation
โโโ README.md
All critical functions are benchmarked:
- Calculator: ~500ns per expression evaluation
- Base62 Encoding: ~100ns per operation
- String Validation: ~50ns per check
๐ค Contributing
We welcome contributions! Please see our contributing guidelines.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Commit your changes (
git commit -m 'Add some amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- Open a Pull Request
โ ๏ธ Stability Notice
This library is under active development. APIs may change between versions. Please check the changelog before upgrading.
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐ Acknowledgments
- Built with โค๏ธ for the Go community
- Inspired by various open-source Go utilities
- Special thanks to all contributors
Made with โค๏ธ by @bizvip
โญ Star us on GitHub if this project helped you!