### Basic Slogx Logger Setup Source: https://github.com/origadmin/toolkits/blob/main/slogx/README.md Sets up a new Slogx logger with file output, JSON format, and Lumberjack for log rotation. Requires the `github.com/origadmin/toolkits/slogx` package and `github.com/natefinch/lumberjack`. ```go import "github.com/origadmin/toolkits/slogx" import "github.com/natefinch/lumberjack" func main() { logger := slogx.New( slogx.WithFile("app.log"), slogx.WithFormat(slogx.FormatJSON), slogx.WithLumberjack(&lumberjack.Logger{ MaxSize: 50, // MB MaxAge: 28, // days }), ) } ``` -------------------------------- ### Add Go Module Dependency Source: https://github.com/origadmin/toolkits/blob/main/README.md Demonstrates how to add the OrigAdmin Go Toolkits module as a dependency to a Go project using the `go get` command. It specifies replacing `vX.Y.Z` with the desired version or 'latest' for the most recent release. ```bash go get github.com/origadmin/toolkits@vX.Y.Z ``` -------------------------------- ### Hash and Verify Password with Bcrypt (Go) Source: https://github.com/origadmin/toolkits/blob/main/crypto/README.md Demonstrates basic password hashing and verification using the bcrypt algorithm. It shows how to create a crypto instance with specific options, hash a password, and then verify it. The resulting hash includes algorithm, parameters, salt, and the hash itself. ```go package main import ( "fmt" "log" "github.com/origadmin/toolkits/crypto/hash" "github.com/origadmin/toolkits/crypto/hash/algorithms/bcrypt" "github.com/origadmin/toolkits/crypto/hash/types" ) func main() { password := "my-secret-password" // 1. Create a crypto instance with a specific algorithm and options. // Here, we use bcrypt with a custom cost. c, err := hash.NewCrypto(types.BCRYPT, bcrypt.WithCost(10)) if err != nil { log.Fatalf("Failed to create crypto: %v", err) } // 2. Hash the password. The result is a single, encoded string that contains // the algorithm name, parameters, salt, and the hash itself. hashed, err := c.Hash(password) if err != nil { log.Fatalf("Hashing failed: %v", err) } fmt.Println("Bcrypt Hash:", hashed) // 3. Verify the password. The `Verify` method automatically detects the algorithm // from the hashed string and uses the correct logic to compare. if err := c.Verify(hashed, password); err != nil { fmt.Println("Verification failed!") } else { fmt.Println("Verification successful!") } } ``` -------------------------------- ### Extended I/O Operations with Context and Auto-Directory Creation (Go) Source: https://context7.com/origadmin/toolkits/llms.txt Demonstrates context-aware file operations using the `io` package. It covers saving data with directory creation, context-aware copying with timeouts, checking file existence, streaming file content, and deleting files. Requires the `github.com/origadmin/toolkits/io` package. Functions accept a `context.Context` for cancellation and timeout control. ```go package main import ( "bytes" "context" "fmt" "strings" "time" "github.com/origadmin/toolkits/io" ) func main() { ctx := context.Background() // Save with context and auto-create directories data := strings.NewReader("Hello, World!") n, err := io.Save(ctx, "/tmp/test/output.txt", data) if err != nil { panic(err) } fmt.Printf("Written %d bytes\n", n) // Context-aware copy with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() src := strings.NewReader("large data stream...") var dst bytes.Buffer copied, err := io.Copy(ctx, &dst, src) if err != nil { panic(err) } fmt.Printf("Copied %d bytes\n", copied) // File existence check exists, err := io.Exists("/tmp/test/output.txt") if err != nil { panic(err) } fmt.Printf("File exists: %t\n", exists) // Stream from file to writer n, err = io.Stream(ctx, "/tmp/test/output.txt", &dst) if err != nil { panic(err) } fmt.Printf("Streamed %d bytes: %s\n", n, dst.String()) // Cleanup if err := io.Delete("/tmp/test/output.txt"); err != nil { fmt.Printf("Delete error: %v\n", err) } } ``` -------------------------------- ### Utility Helper Functions in Go with 'helpers' Package Source: https://context7.com/origadmin/toolkits/llms.txt Demonstrates the use of utility functions from the 'github.com/origadmin/toolkits/helpers' package for common service tasks. It includes generating service discovery paths and resolving actual network endpoints from bind addresses, with support for custom port mappings. ```go package main import ( "fmt" "github.com/origadmin/toolkits/helpers" ) func main() { // Service discovery path generation serviceName := helpers.ServiceDiscovery("userservice") fmt.Printf("Discovery path: %s\n", serviceName) // Output: discovery:///userservice // Resolve actual endpoint from bind address endpoint, err := helpers.ServiceEndpoint("http", "0.0.0.0", ":8080") if err != nil { panic(err) } fmt.Printf("Actual endpoint: %s\n", endpoint) // Output: http://192.168.1.100:8080 (actual IP) // With custom port mapping endpoint2, err := helpers.ServiceEndpoint("https", "0.0.0.0", "8443:8443") if err != nil { panic(err) } fmt.Printf("HTTPS endpoint: %s\n", endpoint2) } ``` -------------------------------- ### Build Information Management in Go Source: https://context7.com/origadmin/toolkits/llms.txt Shows how to capture and expose build metadata such as version, git commit, and build date using the version utility. It demonstrates printing all build info as JSON, reading structured information, and serializing it for API responses. Includes instructions for building with ldflags. ```go package main import ( "encoding/json" "fmt" "github.com/origadmin/toolkits/version" ) func main() { // Print all build info as JSON version.PrintBuildInfo() // Get structured build information info := version.ReadBuildInfo() fmt.Printf("Version: %s\n", info.Version) fmt.Printf("Git Commit: %s\n", info.GitCommit) fmt.Printf("Git Branch: %s\n", info.GitBranch) fmt.Printf("Build Date: %s\n", info.BuildDate) fmt.Printf("Built By: %s\n", info.BuiltBy) fmt.Printf("Go Version: %s\n", info.GoVersion) fmt.Printf("Platform: %s\n", info.Platform) // Serialize for API response jsonData, err := json.MarshalIndent(info, "", " ") if err != nil { panic(err) } fmt.Printf("JSON:\n%s\n", jsonData) } // Build with version information: // go build -ldflags "\ // -X github.com/origadmin/toolkits/version.gitTag=v1.0.0 \ // -X github.com/origadmin/toolkits/version.gitCommit=abc123 \ // -X github.com/origadmin/toolkits/version.gitBranch=main \ // -X github.com/origadmin/toolkits/version.buildDate=2024-01-15 \ // -X github.com/origadmin/toolkits/version.version=1.0.0 \ // " ./cmd/app ``` -------------------------------- ### Upgrade Hashing Algorithm Seamlessly (Go) Source: https://github.com/origadmin/toolkits/blob/main/crypto/README.md Illustrates how to upgrade a user's password hash from an older algorithm (SHA-256) to a newer, more secure one (Argon2) during login. It shows that verification can be done against the old hash using a crypto instance configured for the new algorithm, and then updates the stored hash upon successful verification. ```go func demonstrateUpgrade() { password := "password-to-migrate" // 1. Assume you have an old hash created with SHA-256. sha256Crypto, _ := hash.NewCrypto(types.SHA256) oldHash, _ := sha256Crypto.Hash(password) fmt.Println("Old SHA-256 Hash:", oldHash) // 2. Your application is now configured to use the more secure Argon2 algorithm. argon2Crypto, _ := hash.NewCrypto(types.ARGON2) // 3. A user logs in. You can still verify their password against the old SHA-256 hash. if err := argon2Crypto.Verify(oldHash, password); err == nil { fmt.Println("Verification of old hash successful!") // 4. (Recommended) Since verification was successful, create a new hash with the // upgraded algorithm and store it in your database for future logins. newHash, _ := argon2Crypto.Hash(password) fmt.Println("New Argon2 Hash:", newHash) // database.UpdateUserPasswordHash(userID, newHash) } } ``` -------------------------------- ### Network Utilities: IP Extraction and Request Filtering (Go) Source: https://context7.com/origadmin/toolkits/llms.txt Illustrates network utilities for IP address extraction and HTTP request filtering using the `net` and `filter` packages. It shows how to extract service endpoints, create request filters with allow/deny rules, check permissions, and integrate with HTTP middleware. Also demonstrates the use of a Bloom filter for efficient filtering of large rule sets. Requires `github.com/origadmin/toolkits/net` and `github.com/origadmin/toolkits/net/filter`. ```go package main import ( "fmt" "net/http" "github.com/origadmin/toolkits/net" "github.com/origadmin/toolkits/net/filter" ) func main() { // Extract real IP and generate endpoint endpoint, err := net.ExtractIP("http", "0.0.0.0", ":8080") if err != nil { panic(err) } fmt.Printf("Service endpoint: %s\n", endpoint) // Create request filter with allow/deny rules requestFilter := filter.NewFilter( filter.WithAllows( "GET:/api/users", "GET:/api/posts", "POST:/api/login", "PUT:/api/users/*", ), filter.WithDenies( "GET:/admin/*", "DELETE:/api/*", ), ) // Check permissions if requestFilter.Allowed("GET", "/api/users") { fmt.Println("GET /api/users: allowed") } if requestFilter.Denied("GET", "/admin/settings") { fmt.Println("GET /admin/settings: denied") } // Use with HTTP middleware handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if requestFilter.Skip(r) { http.Error(w, "Forbidden", http.StatusForbidden) return } if requestFilter.Denied(r.Method, r.URL.Path) { http.Error(w, "Access Denied", http.StatusForbidden) return } w.Write([]byte("Request processed")) }) // Bloom filter for large rule sets (more memory efficient) bloomFilter := filter.NewBloomFilter( filter.WithAllows("GET:/api/*", "POST:/api/*"), filter.WithExpectedElements(10000), filter.WithFalsePositiveRate(0.01), ) if bloomFilter.Allowed("GET", "/api/data") { fmt.Println("Bloom filter: request allowed") } _ = handler } ``` -------------------------------- ### Developer-Friendly Format with Source Location Source: https://github.com/origadmin/toolkits/blob/main/slogx/README.md Sets up Slogx with a developer-focused format (FormatDev) that includes source code location tracking and a custom time layout. Requires `github.com/origadmin/toolkits/slogx`. ```go import "github.com/origadmin/toolkits/slogx" logger := slogx.New( slogx.WithFormat(slogx.FormatDev), slogx.WithAddSource(), slogx.WithTimeLayout("2006-01-02 15:04:05.000"), ) ``` -------------------------------- ### Structured Logging with Slogx in Go Source: https://context7.com/origadmin/toolkits/llms.txt Demonstrates how to use the slogx library for structured logging in Go. It covers basic logging, debug logging, production configuration with JSON output and file rotation using lumberjack, and development mode with colored output. It also shows how to set a custom time layout. ```go package main import ( "log/slog" "github.com/origadmin/toolkits/slogx" "gopkg.in/natefinch/lumberjack.v2" ) func main() { // Simple logger with defaults logger := slogx.New() logger.Info("Application started") // Debug logger (lower threshold) debugLogger := slogx.NewDebug() debugLogger.Debug("Debug information", "component", "main") // Production configuration with JSON output and file rotation prodLogger := slogx.New( slogx.WithLevel(slog.LevelInfo), slogx.WithFormat(slogx.FormatJSON), slogx.WithOutput("/var/log/app.log"), slogx.WithAddSource(true), slogx.WithLumberjack(&lumberjack.Logger{ Filename: "/var/log/app.log", MaxSize: 100, // MB MaxBackups: 3, MaxAge: 28, // days Compress: true, }), slogx.WithDefault(true), // Set as default logger ) prodLogger.Info("Server started", "port", 8080, "env", "production", ) // Development logger with colored output devLogger := slogx.New( slogx.WithLevel(slog.LevelDebug), slogx.WithFormat(slogx.FormatTint), // Colorized slogx.WithConsole(true), slogx.WithAddSource(true), ) devLogger.Debug("Processing request", "method", "GET", "path", "/api/users", "duration_ms", 45, ) devLogger.Error("Database connection failed", "error", "connection timeout", "host", "localhost:5432", ) // Custom time layout customLogger := slogx.New( slogx.WithTimeLayout("2006-01-02 15:04:05"), slogx.WithFormat(slogx.FormatText), ) customLogger.Info("Custom timestamp format") } ``` -------------------------------- ### Implement Application Metrics Collector in Go Source: https://context7.com/origadmin/toolkits/llms.txt Demonstrates implementing a custom metrics collector for application telemetry using Go. It includes methods for enabling/disabling the collector, observing custom metrics, and logging request details. Dependencies include the 'context' and 'time' packages, along with the 'github.com/origadmin/toolkits/metrics' package. ```go package main import ( "context" "fmt" "time" "github.com/origadmin/toolkits/metrics" ) // Implement custom metrics collector type PrometheusMetrics struct { enabled bool // ... prometheus client fields } func (m *PrometheusMetrics) Enabled() bool { return m.enabled } func (m *PrometheusMetrics) Disable() { m.enabled = false } func (m *PrometheusMetrics) Observe(ctx context.Context, data metrics.MetricData) { if !m.enabled { return } // Record metric based on data.Type and data.Labels fmt.Printf("Recording metric: %v\n", data) } func (m *PrometheusMetrics) Log(ctx context.Context, handler, method string, code int, sendBytes, recvBytes int64, latency float64) { if !m.enabled { return } // Record request metrics fmt.Printf("Request: %s %s -> %d (%.2fms, %d/%d bytes)\n", method, handler, code, latency, sendBytes, recvBytes) } func main() { collector := &PrometheusMetrics{enabled: true} // Get metric label configuration labels := metrics.MetricLabelNames(metrics.MetricRequestsTotal) fmt.Printf("Labels for requests_total: %v\n", labels) // Output: [instance module handler method code] // Log request metrics ctx := context.Background() collector.Log(ctx, "/api/users", "GET", 200, 1024, 512, 45.5) // Observe custom metric data := metrics.MetricData{ Type: metrics.MetricCounterEvent, Labels: map[string]string{ metrics.MetricLabelEvent: "user_login", metrics.MetricLabelState: "success", }, Value: 1, } collector.Observe(ctx, data) // Get all metric types with their labels allLabels := metrics.MetricLabels() for metricType, labelNames := range allLabels { fmt.Printf("%s: %v\n", metricType, labelNames) } } ``` -------------------------------- ### Import OrigAdmin Go Toolkit Packages Source: https://github.com/origadmin/toolkits/blob/main/README.md Shows how to import specific packages from the OrigAdmin Go Toolkits module into Go source files. This allows developers to utilize the provided utilities for tasks like crypto operations or error handling. ```go import ( "github.com/origadmin/toolkits/crypto/hash" "github.com/origadmin/toolkits/errors" // ... and other packages as needed ) ``` -------------------------------- ### High-Performance Byte Slice Filling with io.Reader in Go Source: https://github.com/origadmin/toolkits/blob/main/crypto/README.md Demonstrates high-performance random byte generation by pre-allocating a byte slice and filling it using the `Read` method of a generator initialized with alphanumeric characters. This approach avoids internal allocations for efficient high-throughput scenarios. ```go package main import ( "fmt" "log" "github.com/origadmin/toolkits/crypto/rand" ) func main() { // Create a generator for alphanumeric characters gen := rand.NewGenerator(rand.KindAlphanumeric) // Pre-allocate a byte slice buffer := make([]byte, 128) // Fill the buffer with random bytes using the Read method n, err := gen.Read(buffer) if err != nil { log.Fatalf("Failed to read random bytes: %v", err) } fmt.Printf("Read %d random bytes: %s\n", n, string(buffer)) } ``` -------------------------------- ### Crypto Hash: Password Hashing and Verification Framework in Go Source: https://context7.com/origadmin/toolkits/llms.txt An extensible framework for password hashing and verification, supporting over 20 algorithms like SHA256, Bcrypt, Argon2, and PBKDF2. It allows creating custom crypto instances with specific algorithms and options, global default algorithm usage, and listing available algorithms. Dependencies include specific hashing algorithm packages. ```go package main import ( "fmt" "github.com/origadmin/toolkits/crypto/hash" "github.com/origadmin/toolkits/crypto/hash/algorithms/bcrypt" "github.com/origadmin/toolkits/crypto/hash/types" ) func main() { // Basic hashing with SHA256 password := "my-secret-password" c, err := hash.NewCrypto(types.SHA256) if err != nil { panic(err) } hashed, err := c.Hash(password) if err != nil { panic(err) } fmt.Printf("Hashed: %s\n", hashed) // Verify password if err := c.Verify(hashed, password); err != nil { fmt.Println("Password mismatch") } else { fmt.Println("Password verified!") } // Use Bcrypt with custom cost bcryptCrypto, _ := hash.NewCrypto(types.BCRYPT, bcrypt.WithCost(12)) bcryptHash, _ := bcryptCrypto.Hash(password) // Global default usage hash.UseCrypto(types.ARGON2id) globalHash, _ := hash.Generate("another-password") if err := hash.Verify(globalHash, "another-password"); err != nil { panic(err) } // List available algorithms algos := hash.AvailableAlgorithms() fmt.Printf("Available: %v\n", algos) } ``` -------------------------------- ### Generate Random String with Symbols in Go Source: https://github.com/origadmin/toolkits/blob/main/crypto/README.md Shows how to generate a 20-character random string that includes symbols using the `rand.RandomStringWithSymbols` function. Error handling is included for cases where the generation might fail. ```go package main import ( "fmt" "log" "github.com/origadmin/toolkits/crypto/rand" ) func main() { // Generate a 20-character random string including symbols randomStrWithSymbols, err := rand.RandomStringWithSymbols(20) if err != nil { log.Fatalf("Failed to generate random string with symbols: %v", err) } fmt.Printf("Random String with Symbols: %s\n", randomStrWithSymbols) } ``` -------------------------------- ### Generate Alphanumeric Random String and Bytes in Go Source: https://github.com/origadmin/toolkits/blob/main/crypto/README.md Demonstrates generating a 16-character alphanumeric random string and 32 random bytes using the `rand.RandomString` and `rand.RandomBytes` functions. It includes error handling for failed generation. ```go package main import ( "fmt" "log" "github.com/origadmin/toolkits/crypto/rand" ) func main() { // Generate a 16-character alphanumeric random string randomStr, err := rand.RandomString(16) if err != nil { log.Fatalf("Failed to generate random string: %v", err) } fmt.Printf("Alphanumeric Random String: %s\n", randomStr) // Generate 32 alphanumeric random bytes randomBytes, err := rand.RandomBytes(32) if err != nil { log.Fatalf("Failed to generate random bytes: %v", err) } fmt.Printf("Alphanumeric Random Bytes: %x\n", randomBytes) } ``` -------------------------------- ### Advanced Error Handling in Go with 'errors' Package Source: https://context7.com/origadmin/toolkits/llms.txt Demonstrates advanced error handling capabilities including error chaining, context propagation, and thread-safe multi-error collection using the 'github.com/origadmin/toolkits/errors' package. It shows how to wrap errors, check for specific error types within a chain, attach context, and collect multiple errors concurrently. ```go package main import ( "context" "fmt" "github.com/origadmin/toolkits/errors" "sync" ) func main() { // Error chain traversal baseErr := fmt.Errorf("connection failed") wrappedErr := fmt.Errorf("database error: %w", baseErr) if errors.Has(wrappedErr, baseErr) { fmt.Println("Connection issue detected") } // Walk through error chain _ = errors.Walk(wrappedErr, func(e error) error { fmt.Printf("Error: %v\n", e) return nil // Continue walking }) // Context propagation ctx := context.WithValue(context.Background(), "request_id", "req-123") errWithCtx := errors.NewWithContext(ctx, "operation failed") if val := errors.Value(errWithCtx, "request_id"); val != nil { fmt.Printf("Request ID: %v\n", val) } // Thread-safe multi-error collection merr := errors.ThreadSafe(nil) var wg sync.WaitGroup for i := 0; i < 5; i++ { wg.Add(1) go func(id int) { defer wg.Done() if id%2 == 0 { merr.Append(fmt.Errorf("error from goroutine %d", id)) } }(i) } wg.Wait() if merr.HasErrors() { fmt.Printf("Collected errors: %v\n", merr.Errors()) fmt.Printf("As JSON: %s\n", errors.ErrorFormatJSON(merr.Errors())) } // Type-safe assertions if e, ok := errors.AssertType[*errors.ThreadSafeMultiError](merr); ok { fmt.Printf("Error count: %d\n", len(e.Errors())) } } ``` -------------------------------- ### Generate Custom Character Set String in Go Source: https://github.com/origadmin/toolkits/blob/main/crypto/README.md Illustrates creating a custom character set (hexadecimal characters) and using it with `rand.NewGeneratorWithCharset` to generate a 64-character hex string. This demonstrates flexibility in defining character sets for random string generation. ```go package main import ( "fmt" "log" "github.com/origadmin/toolkits/crypto/rand" ) func main() { // Create a generator with a custom character set (e.g., only hex characters) hexCharset := "0123456789abcdef" hexGenerator := rand.NewGeneratorWithCharset(hexCharset) // Generate a 64-character hex string hexString, err := hexGenerator.RandString(64) if err != nil { log.Fatalf("Failed to generate hex string: %v", err) } fmt.Printf("Custom Hex String: %s\n", hexString) } ``` -------------------------------- ### JSON Logging with File Rotation Source: https://github.com/origadmin/toolkits/blob/main/slogx/README.md Configures Slogx for JSON formatted logs written to a file, with automatic rotation managed by Lumberjack. Specifies filename, size, and backup count. Requires `github.com/origadmin/toolkits/slogx` and `github.com/natefinch/lumberjack`. ```go import "github.com/origadmin/toolkits/slogx" import "github.com/natefinch/lumberjack" logger := slogx.New( slogx.WithFile("app.json.log"), slogx.WithFormat(slogx.FormatJSON), slogx.WithLumberjack(&lumberjack.Logger{ Filename: "app.json.log", MaxSize: 10, // megabytes per file MaxBackups: 5, MaxAge: 30, // days }), ) ``` -------------------------------- ### Codec: Encode/Decode Data (JSON, YAML, TOML, XML, INI) in Go Source: https://context7.com/origadmin/toolkits/llms.txt Provides a unified interface for encoding and decoding data across multiple formats including JSON, YAML, TOML, XML, and INI. It supports automatic format detection from file extensions, manual format specification, and type utilities for checking supported formats. Dependencies include standard Go libraries. ```go package main import ( "fmt" "github.com/origadmin/toolkits/codec" ) type Config struct { Name string `json:"name" yaml:"name"` Port int `json:"port" yaml:"port"` Enabled bool `json:"enabled" yaml:"enabled"` } func main() { // Auto-detect format from file extension var config Config if err := codec.DecodeFromFile("config.yaml", &config); err != nil { panic(err) } fmt.Printf("Loaded: %+v\n", config) // Encode to different format config.Port = 9090 if err := codec.EncodeToFile("config.json", config); err != nil { panic(err) } // Manual format specification data := []byte(`{"name":"app","port":8080,"enabled":true}`) var cfg2 Config if err := codec.JSON.Unmarshal(data, &cfg2); err != nil { panic(err) } // Type utilities fileType := codec.TypeFromPath("settings.toml") // Returns TOML if codec.IsSupported("yaml") { fmt.Println("YAML is supported") } } ``` -------------------------------- ### Colored Console Output with Slogx Source: https://github.com/origadmin/toolkits/blob/main/slogx/README.md Configures Slogx to output logs only to the console with a colorful, terminal-friendly format (FormatTint). ```go import "github.com/origadmin/toolkits/slogx" logger := slogx.New( slogx.WithFormat(slogx.FormatTint), slogx.WithConsoleOnly(), ) ``` -------------------------------- ### Crypto AES: Symmetric Encryption and Decryption in Go Source: https://context7.com/origadmin/toolkits/llms.txt Implements AES symmetric encryption and decryption using CBC and GCM modes. The GCM mode is recommended for its security, requiring a random nonce. It supports direct byte slice operations and convenient Base64 encoding/decoding for encrypted data. Key must be 32 bytes for AES-256. Dependencies include standard Go crypto libraries. ```go package main import ( "encoding/base64" "fmt" "github.com/origadmin/toolkits/crypto/aes" ) func main() { key := []byte("0123456789abcdef0123456789abcdef") // 32 bytes for AES-256 plaintext := []byte("sensitive data to encrypt") // GCM mode (recommended - secure with random nonce) encrypted, err := aes.EncryptGCM(plaintext, key) if err != nil { panic(err) } fmt.Printf("Encrypted: %x\n", encrypted) decrypted, err := aes.DecryptGCM(encrypted, key) if err != nil { panic(err) } fmt.Printf("Decrypted: %s\n", decrypted) // Base64 encoded output encoded, err := aes.EncodeCBCBase64(plaintext, key) if err != nil { panic(err) } fmt.Printf("Base64: %s\n", encoded) decoded, err := aes.DecodeCBCBase64(encoded, key) if err != nil { panic(err) } fmt.Printf("Decoded: %s\n", decoded) } ``` -------------------------------- ### Convert Maps and Slices to Wrapped Structures in Go Source: https://context7.com/origadmin/toolkits/llms.txt Provides utilities for converting maps and slices into wrapped structures with custom naming using Go. It utilizes the 'github.com/origadmin/toolkits/decode' package to create a generic converter with custom namer and wrapper functions. The input is a map or slice of a specific type, and the output is a slice of the same type. ```go package main import ( "fmt" "github.com/origadmin/toolkits/decode" ) type Handler struct { Name string Pattern string Active bool } func main() { // Create converter with custom namer and wrapper converter := decode.NewConverter[*Handler, []*Handler]( // Namer function: assign name from map key func(name string, item *Handler) (*Handler, bool) { if item == nil { return nil, false } item.Name = name return item, true }, // Wrapper function: return slice as-is func(items []*Handler) []*Handler { return items }, ) // Convert from map handlerMap := map[string]*Handler{ "home": {Pattern: "/", Active: true}, "users": {Pattern: "/users", Active: true}, "admin": {Pattern: "/admin", Active: false}, } handlers := converter.FromMap(handlerMap) for _, h := range handlers { fmt.Printf("Handler: %s -> %s (active: %t)\n", h.Name, h.Pattern, h.Active) } // Convert from slice (names already set) handlerSlice := []*Handler{ {Name: "api", Pattern: "/api", Active: true}, {Name: "docs", Pattern: "/docs", Active: true}, } converted := converter.FromSlice(handlerSlice) fmt.Printf("Converted %d handlers from slice\n", len(converted)) } ``` -------------------------------- ### Unique ID Generation in Go with 'identifier' Package Source: https://context7.com/origadmin/toolkits/llms.txt Illustrates how to generate various types of unique identifiers (UUID, Snowflake, ULID, KSUID) using the 'github.com/origadmin/toolkits/identifier' package. It covers using default generators, registering custom ones, setting defaults, retrieving specific generators, and configuring generators like Snowflake with custom node IDs. ```go package main import ( "fmt" "github.com/origadmin/toolkits/identifier" "github.com/origadmin/toolkits/identifier/snowflake" "github.com/origadmin/toolkits/identifier/uuid" ) func main() { // Use default generators userID := identifier.GenerateString() // Default UUID sessionID := identifier.GenerateNumber() // Default Snowflake fmt.Printf("User ID: %s\n", userID) fmt.Printf("Session ID: %d\n", sessionID) // Register and use specific generator identifier.Register(uuid.NewV7()) // Time-sortable UUID identifier.SetDefaultString("uuid-v7") v7ID := identifier.GenerateString() fmt.Printf("UUID v7: %s\n", v7ID) // Get specific generator uuidGen := identifier.Get[string]("uuid") if uuidGen != nil { id := uuidGen.Generate() isValid := uuidGen.Validate(id) fmt.Printf("UUID: %s, Valid: %t\n", id, isValid) } // Snowflake with custom node provider, err := snowflake.New(snowflake.Config{Node: 42}) if err != nil { panic(err) } stringGen := provider.AsString() numberGen := provider.AsNumber() fmt.Printf("Snowflake (string): %s\n", stringGen.Generate()) fmt.Printf("Snowflake (number): %d\n", numberGen.Generate()) // Get other formats ulidGen := identifier.Get[string]("ulid") ksuidGen := identifier.Get[string]("ksuid") if ulidGen != nil { fmt.Printf("ULID: %s\n", ulidGen.Generate()) } if ksuidGen != nil { fmt.Printf("KSUID: %s\n", ksuidGen.Generate()) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.