Skip to content

Repository files navigation

Utils

A comprehensive Go utility library providing essential tools for common development tasks.

Go VersionGo ReferenceGo Report CardLicensecodecov

Installation

go get github.com/CodeLieutenant/utils

Modules

This package contains several utility modules:

  • Core utilities - File operations, path handling, password generation, memory formatting
  • Environment management - Environment variable handling with type conversion
  • Network utilities - IP address detection and validation
  • Cryptographic utilities - Key parsing and hashing algorithms
  • HTTP utilities - Chi router helpers and HTTP response utilities
  • Logging - Structured logging with stacktraces and runtime info
  • URL signing - HMAC-based URL signing for secure links
  • Signal handling - Cross-platform OS signal management

📚 Detailed Documentation

Each subpackage has comprehensive documentation with examples:

Core Utilities

File Operations

package main
import (
"fmt""os""github.com/CodeLieutenant/utils"
)
funcmain() {
// Create a directory with permissionsdirPath, err:=utils.CreateDirectory("/tmp/myapp", 0755)
iferr!=nil {
panic(err)
}
fmt.Printf("Directory created: %s\n", dirPath)
// Create a log filelogFile, err:=utils.CreateLogFile("/tmp/myapp/app.log")
iferr!=nil {
panic(err)
}
deferlogFile.Close()
// Check if file existsifutils.FileExists("/tmp/myapp/app.log") {
fmt.Println("Log file exists!")
}
}

Password Generation

package main
import (
"fmt""github.com/CodeLieutenant/utils"
)
funcmain() {
// Generate a secure random passwordpassword, err:=utils.GenerateRandomPassword(16)
iferr!=nil {
panic(err)
}
fmt.Printf("Generated password: %s\n", password)
}

Memory Size Formatting

package main
import (
"fmt""github.com/CodeLieutenant/utils"
)
funcmain() {
// Format memory sizessize:=utils.MemorySize(1024*1024*1024) // 1 GiBfmt.Printf("Memory size: %s\n", size.String()) // Output: 1GiB// Different sizesfmt.Printf("1024 bytes: %s\n", utils.MemorySize(1024).String()) // 1KiBfmt.Printf("1MB: %s\n", utils.MemorySize(1024*1024).String()) // 1MiB
}

Unsafe String/Bytes Conversion

package main
import (
"fmt""github.com/CodeLieutenant/utils"
)
funcmain() {
// Zero-copy string to bytes conversionstr:="hello world"bytes:=utils.UnsafeBytes(str)
fmt.Printf("String as bytes: %v\n", bytes)
// Zero-copy bytes to string conversionbackToString:=utils.UnsafeString(bytes)
fmt.Printf("Bytes as string: %s\n", backToString)
}

Environment Management

package main
import (
"fmt""github.com/CodeLieutenant/utils"
)
funcmain() {
// Initialize environment (loads .env file automatically)env:=utils.NewEnv(false)
// Get string with defaultdbHost:=utils.GetStringEnv(env, "DB_HOST", "localhost")
fmt.Printf("Database host: %s\n", dbHost)
// Get integer with defaultdbPort:=utils.GetIntEnv(env, "DB_PORT", 5432)
fmt.Printf("Database port: %d\n", dbPort)
// Get boolean with defaultdebug:=utils.GetBoolEnv(env, "DEBUG", false)
fmt.Printf("Debug mode: %t\n", debug)
// Get duration with defaulttimeout:=utils.GetDurationEnv(env, "REQUEST_TIMEOUT", "30s")
fmt.Printf("Request timeout: %v\n", timeout)
// Get string sliceallowedHosts:=utils.GetStringsEnv(env, "ALLOWED_HOSTS", []string{"localhost"})
fmt.Printf("Allowed hosts: %v\n", allowedHosts)
}

Network Utilities

package main
import (
"fmt""github.com/CodeLieutenant/utils"
)
funcmain() {
// Get local machine IPlocalIP:=utils.GetLocalIP()
fmt.Printf("Local IP: %s\n", localIP)
// Get all local IPslocalIPs:=utils.GetLocalIPs()
fmt.Printf("All local IPs: %v\n", localIPs)
}

Cryptographic Utilities

package main
import (
"fmt""github.com/CodeLieutenant/utils"
)
funcmain() {
// Parse hex-encoded keyhexKey:="deadbeefcafebabe1234567890abcdef12345678"key1, err:=utils.ParseKey(hexKey)
iferr!=nil {
panic(err)
}
fmt.Printf("Hex key length: %d bytes\n", len(key1))
// Parse base64-encoded keybase64Key:="base64:3q2+78r+uro="key2, err:=utils.ParseKey(base64Key)
iferr!=nil {
panic(err)
}
fmt.Printf("Base64 key length: %d bytes\n", len(key2))
// Get hash functionhasher:=utils.ParseHasher("sha256")
ifhasher!=nil {
h:=hasher()
h.Write([]byte("hello world"))
hash:=h.Sum(nil)
fmt.Printf("SHA256 hash length: %d bytes\n", len(hash))
}
}

HTTP Utilities

📖 For comprehensive HTTP utilities documentation, see: HTTP Utils Package Documentation

package main
import (
"net/http""github.com/CodeLieutenant/utils/httputils""github.com/go-chi/chi/v5"
)
funcmain() {
// Setup router with production middlewareconfig:=httputils.ProductionMiddlewareConfig()
options:=&httputils.RouterSetupOptions{
LoggerColor: false,
Middleware: config,
}
r:=httputils.SetupRouter(options)
// Add routesr.Get("/api/health", func(w http.ResponseWriter, r*http.Request) {
response:=map[string]string{"status": "ok"}
httputils.NewResponse(w).OK(response)
})
http.ListenAndServe(":8080", r)
}

Logging

📖 For comprehensive logging documentation, see: Logger Package Documentation

package main
import (
"context""log/slog""github.com/CodeLieutenant/utils/logger"
)
funcmain() {
// Configure structured loggingconfig:=&logger.LogConfig{
Level: "info",
Format: "json",
Output: "stdout",
AddSource: true,
AddStacktrace: true,
AddRuntimeInfo: true,
}
// Setup loggerslogger, err:=logger.SetupLogger("myapp", "v1.0.0", config)
iferr!=nil {
panic(err)
}
// Use the loggerctx:=context.Background()
slogger.InfoContext(ctx, "Application started",
slog.String("version", "v1.0.0"),
slog.Int("port", 8080),
)
slogger.ErrorContext(ctx, "Something went wrong",
slog.String("error", "database connection failed"),
)
}

URL Signing

📖 For comprehensive URL signing documentation, see: URL Signer Package Documentation

package main
import (
"fmt""net/url""time""github.com/CodeLieutenant/utils""github.com/CodeLieutenant/utils/urlsigner"
)
funcmain() {
// Create HMAC signer with SHA256key, _:=utils.ParseKey("deadbeefcafebabe1234567890abcdef12345678")
signer:=urlsigner.New("sha256", key)
// Sign a URL with 1 hour expirationoriginalURL:="https://example.com/api/download?file=document.pdf"signedURL, err:=signer.Sign(originalURL, time.Hour)
iferr!=nil {
panic(err)
}
fmt.Printf("Signed URL: %s\n", signedURL)
// Verify the signed URLparsedURL, _:=url.Parse(signedURL)
iferr:=signer.Verify(parsedURL); err!=nil {
fmt.Printf("Verification failed: %v\n", err)
} else {
fmt.Println("URL signature is valid!")
}
}

Signal Handling

📖 For comprehensive signal handling documentation, see: Signals Package Documentation

package main
import (
"fmt""os""github.com/CodeLieutenant/utils/signals"
)
funcmain() {
// Get signal by namesigterm, err:=signals.Get("SIGTERM")
iferr!=nil {
panic(err)
}
fmt.Printf("SIGTERM signal: %v\n", sigterm)
// Must get signal (panics if not found)sigint:=signals.MustGet("SIGINT")
fmt.Printf("SIGINT signal: %v\n", sigint)
// Use in signal handlingsigChan:=make(chan os.Signal, 1)
signal.Notify(sigChan, sigint, sigterm)
fmt.Println("Waiting for signal...")
sig:=<-sigChanfmt.Printf("Received signal: %v\n", sig)
}

Environment Constants

The package provides predefined environment constants:

const (
EnvDev="development"EnvProd="production"EnvStage="staging"
)

Testing

Run the test suite:

# Run all tests
make test# Run tests with coverage
make test-coverage
# View coverage report
make coverage-html

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Dependencies

About

Go Utils for General Development

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages