### Install GORM Memoization SDK Source: https://github.com/presbrey/pkg/blob/main/gormoize/README.md Installs the GORM Memoization SDK using the go get command. ```bash go get github.com/presbrey/pkg/gormoize ``` -------------------------------- ### Install booltmemo Package Source: https://github.com/presbrey/pkg/blob/main/booltmemo/README.md Installs the booltmemo Go package using the go get command. ```bash go get github.com/yourusername/booltmemo ``` -------------------------------- ### Install Echo CDN Middleware Source: https://github.com/presbrey/pkg/blob/main/cdns/README.md Installs the Echo CDN middleware package using go get. ```bash go get github.com/presbrey/pkg/cdns ``` -------------------------------- ### Core Server API Usage Source: https://github.com/presbrey/pkg/blob/main/irc/README.md Example Go code demonstrating how to load configuration, create a new server instance, register custom hooks for events like PRIVMSG, and start the server. ```go package main import ( "log" "github.com/yourusername/goircd/config" "github.com/yourusername/goircd/server" ) func main() { // Load configuration cfg, err := config.Load("config.yaml") if err != nil { log.Fatalf("Failed to load configuration: %v", err) } // Create server srv, err := server.NewServer(cfg) if err != nil { log.Fatalf("Failed to create server: %v", err) } // Register custom hooks srv.RegisterHook("PRIVMSG", myCustomHandler) // Start server if err := srv.Start(); err != nil { log.Fatalf("Server failed: %v", err) } } func myCustomHandler(params *server.HookParams) error { // Custom handler for PRIVMSG client := params.Client message := params.Message // Log all private messages log.Printf("PRIVMSG from %s to %s: %s", client.Nickname, message.Params[0], message.Params[1], ) return nil } ``` -------------------------------- ### Copy Example Configuration Source: https://github.com/presbrey/pkg/blob/main/irc/README.md Command to copy the example configuration file to `config.yaml` for customization. ```bash cp config.yaml.example config.yaml ``` -------------------------------- ### Install Base92 CLI Source: https://github.com/presbrey/pkg/blob/main/base92/cli/README.md Instructions for installing the Base92 CLI tool using Go modules or by building from source. ```bash go install github.com/presbrey/pkg/base92/cli@latest ``` ```bash cd cli go build -o base92 ``` -------------------------------- ### Go Wait Library Installation Source: https://github.com/presbrey/pkg/blob/main/wait/README.md Command to install the Go Wait library using go get. ```bash go get github.com/yourusername/wait ``` -------------------------------- ### Usage Examples: Simple and Nested Access Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Provides examples of accessing configuration values using simple keys and nested paths with dot notation. ```go // Simple key access enabled := sdk.GetBoolWithDefault(c, "feature1", false) // Nested path access with dot notation dashboardEnabled := sdk.GetBoolWithDefault(c, "metadata.features.dashboard", false) maxUsers := sdk.GetIntWithDefault(c, "limits.maxUsers", 100) ``` -------------------------------- ### Install Feature Flags SDK Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Command to install the feature flags SDK for Go applications using the go get command. ```bash go get github.com/presbrey/pkg/echoflags ``` -------------------------------- ### Install RemoteMap Go Package Source: https://github.com/presbrey/pkg/blob/main/syncmap/README.md This command installs the RemoteMap Go package using the go get command. Ensure you have Go installed and configured correctly. ```bash go get github.com/user/syncmap ``` -------------------------------- ### Install Go Package Source: https://github.com/presbrey/pkg/blob/main/slugs/README.md Installs the 'slugs' Go package using the go get command. ```bash go get github.com/yourusername/slugs ``` -------------------------------- ### Go Wait Library Quick Start Source: https://github.com/presbrey/pkg/blob/main/wait/README.md Demonstrates basic usage of the Go Wait library, including waiting for network connectivity and a TCP service with exponential backoff. ```go package main import ( "log" "time" "github.com/yourusername/wait" ) func main() { // Wait for network connectivity err := wait.ForNetwork() if err != nil { log.Fatal(err) } // Wait for a TCP service with exponential backoff err = wait.ForTCP("localhost:8080", wait.DefaultOptions(). WithTimeout(30 * time.Second). WithStrategy(wait.NewExponentialBackoffStrategy( 1*time.Second, // initial 2.0, // multiplier 10*time.Second, // max true, // jitter ))) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### Install Hook Registry Package Source: https://github.com/presbrey/pkg/blob/main/hooks/README.md Installs the hook registry package using the Go build tool. ```bash go get github.com/presbrey/pkg/hooks ``` -------------------------------- ### Install Slug Command CLI Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Provides instructions for installing the Slug Command CLI tool using Go's package manager or by building from source. ```bash go install github.com/presbrey/pkg/slugs/cmd/slug@latest ``` ```bash cd slugs/cmd/slug go build ``` -------------------------------- ### Managing Hook Registry in Go Source: https://github.com/presbrey/pkg/blob/main/hooks/README.md Provides examples for managing the hook registry, including getting the count of registered hooks and clearing all registered hooks. ```go import "github.com/presbrey/pkg/hooks" // Assuming MyContext is defined elsewhere type MyContext struct {} func main() { registry := hooks.NewRegistry[*MyContext]() // Register some hooks... // Get the number of registered hooks count := registry.Count() // Clear all registered hooks registry.Clear() } ``` -------------------------------- ### Go Installation Command Source: https://github.com/presbrey/pkg/blob/main/fly/README.md Shows the command to install the Fly package using Go modules. ```bash go get github.com/presbrey/pkg/fly ``` -------------------------------- ### Fallback Tenant Configuration Example Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Demonstrates how to configure the SDK to use a fallback tenant for retrieving configuration values when keys are not found in the primary tenant. ```go sdk := echoflags.New(echoflags.Config{ HTTPBaseURL: "https://raw.githubusercontent.com/org/repo/main/tenants", FallbackTenant: "global", // Fallback to "global" tenant }) // If "newFeature" doesn't exist in the primary tenant (e.g., "tenant1"), // it will automatically check the "global" tenant enabled := sdk.IsEnabled(c, "newFeature") ``` -------------------------------- ### Install echovalidator Source: https://github.com/presbrey/pkg/blob/main/echovalidator/README.md Installs the echovalidator package using the go get command. Ensure the import path is correct for your project. ```bash go get github.com/presbrey/pkg/echovalidator ``` -------------------------------- ### Syncmap Remote Map Synchronization Source: https://github.com/presbrey/pkg/blob/main/README.md Demonstrates how to use the syncmap package to create a remote map that synchronizes data from a JSON URL. It shows how to start the synchronization, retrieve string values, and get all keys. The refresh period and other options can be configured. ```Go import ( "fmt" "time" "github.com/presbrey/pkg/syncmap" ) func main() { rm := syncmap.NewRemoteMap("https://api.example.com/data", &syncmap.Options{ RefreshPeriod: 30 * time.Second, }) rm.Start() defer rm.Stop() if name, ok := rm.GetString("name"); ok { fmt.Printf("Name: %s\n", name) } // Get all keys keys := rm.Keys() fmt.Println("All keys:", keys) } ``` -------------------------------- ### Syncthing Generic Remote Map Synchronization Source: https://github.com/presbrey/pkg/blob/main/README.md Illustrates the usage of the syncthing package for type-safe synchronization of remote JSON data using generics and a fluent API. It shows how to configure the refresh period, set an update callback, start the synchronization, retrieve values, and get all keys. ```Go import ( "fmt" "time" "github.com/presbrey/pkg/syncthing" ) func main() { rm := syncthing.NewMapString[string]("https://api.example.com/data"). WithRefreshPeriod(30 * time.Second). WithUpdateCallback(func(updated []string) { fmt.Printf("Updated keys: %v\n", updated) }). Start() defer rm.Stop() if value, ok := rm.Get("name"); ok { fmt.Printf("Name: %s\n", value) } // Get all keys keys := rm.Keys() fmt.Println("All keys:", keys) } ``` -------------------------------- ### Basic Syncthing Map Initialization and Usage Source: https://github.com/presbrey/pkg/blob/main/syncthing/README.md Demonstrates how to create a new MapString with string values, configure synchronization parameters using a fluent interface, start the synchronization, and retrieve values. ```Go func main() { // Create a new MapString with string values using the Fluent Interface rm := syncthing.NewMapString[string]("https://api.example.com/data"). WithRefreshPeriod(1 * time.Minute). WithTimeout(10 * time.Second). WithErrorHandler(func(err error) { log.Printf("Error: %v", err) }). WithUpdateCallback(func(updated []string) { log.Printf("Updated keys: %v", updated) }). WithDeleteCallback(func(deleted []string) { log.Printf("Deleted keys: %v", deleted) }). WithRefreshCallback(func() { log.Printf("Map refreshed at %v", time.Now()) }). Start() // Don't forget to stop the synchronization when done defer rm.Stop() // Get a string value value, ok := rm.Get("key") if ok { fmt.Println("Value:", value) } // Get with default value value = rm.GetWithDefault("key", "default") fmt.Println("Value with default:", value) } ``` -------------------------------- ### Feature Flags with A/B Testing Example Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Demonstrates using feature flags for A/B testing by retrieving a variant configuration and routing user requests accordingly. ```go func handleRequest(c echo.Context) error { // Get user-specific configuration with fallback support variant := sdk.GetStringWithDefault(c, "experimentVariant", "control") switch variant { case "A": return handleVariantA(c) case "B": return handleVariantB(c) default: return handleDefault(c) } } ``` -------------------------------- ### Custom HTTP Client Configuration Example Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Shows how to configure a custom HTTP client for the SDK, enabling control over timeouts, connection pooling, and other transport-level settings. ```go sdk := echoflags.New(echoflags.Config{ HTTPBaseURL: "https://raw.githubusercontent.com/org/repo/main/tenants", HTTPClient: &http.Client{ Timeout: 10 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, IdleConnTimeout: 90 * time.Second, }, }, }) ``` -------------------------------- ### Encode Data with Base92 CLI Source: https://github.com/presbrey/pkg/blob/main/base92/cli/README.md Examples of how to encode data using the Base92 CLI, either from a file or from standard input. ```bash base92 encode myfile.txt > encoded.txt ``` ```bash echo "Hello World!" | base92 encode ``` -------------------------------- ### Generate NanoID-Style Slug Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a slug using the NanoID style. ```bash slug -n # Output: hHWZu_ZW ``` -------------------------------- ### Go Fly Core Library Usage Source: https://github.com/presbrey/pkg/blob/main/fly/README.md Demonstrates how to use the core 'fly' package to get a list of machines for an application and retrieve logs for a specific machine. Requires the 'github.com/presbrey/pkg/fly' package. ```go package main import ( "fmt" "log" "github.com/presbrey/pkg/fly" ) func main() { // Get list of machines for an app machines, err := fly.GetMachineList("my-app") if err != nil { log.Fatalf("Error getting machines: %v", err) } // Print machine details for _, machine := range machines { fmt.Printf("Machine: %s, Region: %s, State: %s\n", machine.Name, machine.Region, machine.State) } // Get logs for a specific machine (non-streaming mode) if len(machines) > 0 { logs, err := fly.GetMachineLogs("my-app", machines[0].ID, false) if err != nil { log.Fatalf("Error getting logs: %v", err) } fmt.Println(logs) } } ``` -------------------------------- ### Bot API Send Message Example Source: https://github.com/presbrey/pkg/blob/main/irc/README.md Example `curl` command to interact with the GoIRCd Bot API, specifically for sending a message to a channel. ```bash curl -X POST \ http://localhost:8081/api/send \ -H 'Authorization: Bearer your-secret-token-1' \ -H 'Content-Type: application/json' \ -d '{ "nickname": "MyBot", "channel": "#mychannel", "message": "Hello, world!" }' ``` -------------------------------- ### Custom Tenant and User Extraction Example Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Illustrates how to provide custom functions to extract tenant and user information from the Echo context, allowing for flexible integration with existing authentication and multi-tenancy systems. ```go sdk := echoflags.New(echoflags.Config{ HTTPBaseURL: "https://raw.githubusercontent.com/org/repo/main/tenants", GetTenantFromContext: func(c echo.Context) string { // Extract tenant from custom header return c.Request().Header.Get("X-Tenant-ID") }, GetUserFromContext: func(c echo.Context) string { // Extract user from JWT claims token := c.Get("jwt-claims").(jwt.MapClaims) return token["sub"].(string) }, }) ``` -------------------------------- ### Go Wait Library Options Configuration Source: https://github.com/presbrey/pkg/blob/main/wait/README.md Example of configuring wait options in the Go Wait library, including setting max retries, timeout, retry strategy, and context. ```go opts := wait.DefaultOptions(). WithMaxRetries(10). WithTimeout(30 * time.Second). WithStrategy(strategy). WithContext(ctx) ``` -------------------------------- ### FlySuper Utility CLI Commands Source: https://github.com/presbrey/pkg/blob/main/fly/README.md Provides examples of using the 'flysu' command-line utility for managing Fly.io machines and logs across different regions and applications. Includes options for filtering and output formatting. ```bash # List all machines across all regions flysu list # View logs for all apps in US regions only flysu logs --us # List machines in EU regions only with minimal output flysu list --eu --quiet # Follow logs for a specific app flysu logs -f -a us-east-1-portal # View help information flysu help ``` -------------------------------- ### Progressive Rollouts Example Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Illustrates implementing progressive rollouts by checking if a user falls within a specified percentage for a feature, using a hashed user identifier. ```go func isFeatureEnabledForUser(c echo.Context) bool { // Check if user is in rollout percentage (with fallback to 0%) rolloutPercentage := sdk.GetFloat64WithDefault(c, "rolloutPercentage", 0.0) userHash := hashUser(c.Get("user").(string)) return float64(userHash%100) < rolloutPercentage } ``` -------------------------------- ### Decode Data with Base92 CLI Source: https://github.com/presbrey/pkg/blob/main/base92/cli/README.md Examples of how to decode Base92 encoded data using the Base92 CLI, either from a file or from standard input. ```bash base92 decode encoded.txt > decoded.txt ``` ```bash echo "kF%!t%MqcjTu=YZ" | base92 decode ``` -------------------------------- ### Go: Memoize Boolean Function with Different TTLs Source: https://github.com/presbrey/pkg/blob/main/booltmemo/README.md Demonstrates how to use the booltmemo package to memoize a boolean function. It shows setting different TTLs for true and false results, retrieving cached values, invalidating specific keys, and clearing the cache. The example includes a simulated expensive computation and proper cleanup of the memoizer. ```go package main import ( "fmt" "time" "github.com/yourusername/booltmemo" ) // A function that might be expensive to compute func isEven(val interface{}) bool { // Simulate expensive computation time.Sleep(100 * time.Millisecond) num, ok := val.(int) if !ok { return false } return num%2 == 0 } func main() { // Create a memoizer: // - Cache "true" results for 1 minute // - Cache "false" results for 30 seconds memo := booltmemo.New(isEven, 1*time.Minute, 30*time.Second) defer memo.Stop() // Stop the cleanup timer when done // First call (computes the result) start := time.Now() result := memo.Get(42) fmt.Printf("First call: %v, took %v\n", result, time.Since(start)) // Second call (uses cached result) start = time.Now() result = memo.Get(42) fmt.Printf("Second call: %v, took %v\n", result, time.Since(start)) // Invalidate a specific key memo.Invalidate(42) // Clear the entire cache memo.Clear() } ``` -------------------------------- ### Go Wait Library Retry Strategies Source: https://github.com/presbrey/pkg/blob/main/wait/README.md Examples of creating different retry strategies for the Go Wait library, including Fixed, Linear, Exponential Backoff, Fibonacci, Decorrelated Jitter, and Custom strategies. ```go // Fixed Strategy strategy := wait.NewFixedStrategy(2 * time.Second) ``` ```go // Linear Strategy strategy := wait.NewLinearStrategy( 1*time.Second, // initial 500*time.Millisecond, // increment 10*time.Second, // max ) ``` ```go // Exponential Backoff Strategy strategy := wait.NewExponentialBackoffStrategy( 100*time.Millisecond, // initial 2.0, // multiplier 30*time.Second, // max true, // add jitter ) ``` ```go // Fibonacci Strategy strategy := wait.NewFibonacciStrategy( 100*time.Millisecond, // unit 10*time.Second, // max ) ``` ```go // Decorrelated Jitter Strategy strategy := wait.NewDecorrelatedJitterStrategy( 100*time.Millisecond, // base 10*time.Second, // max ) ``` ```go // Custom Strategy durations := []time.Duration{ 100*time.Millisecond, 500*time.Millisecond, 1*time.Second, 5*time.Second, } strategy := wait.NewCustomStrategy(durations, false) // don't repeat ``` -------------------------------- ### Initialize and Use RemoteMap in Go Source: https://github.com/presbrey/pkg/blob/main/syncmap/README.md Demonstrates how to initialize and use the RemoteMap package in a Go application. It covers creating a RemoteMap with default and custom options, starting automatic refresh, accessing values using type-specific getters and standard sync.Map methods, and iterating over the map's contents. ```go package main import ( "fmt" "log" "time" "github.com/user/syncmap" ) func main() { // Create with default options rm := syncmap.NewRemoteMap("https://api.example.com/data", nil) // Or with custom options options := &syncmap.Options{ RefreshPeriod: 30 * time.Second, Timeout: 10 * time.Second, IgnoreTLSVerify: false, Headers: map[string]string{ "User-Agent": "MyApp/1.0", }, ErrorHandler: func(err error) { log.Printf("Error refreshing map: %v", err) }, TransformFunc: func(data map[string]interface{}) map[string]interface{} { // Transform the data if needed return data }, } rm = syncmap.NewRemoteMap("https://api.example.com/data", options) // Start automatic refresh rm.Start() defer rm.Stop() // Access values using type-specific getters if name, ok := rm.GetString("name"); ok { fmt.Printf("Name: %s\n", name) } if count, ok := rm.GetInt("count"); ok { fmt.Printf("Count: %d\n", count) } // Or use standard sync.Map methods value, ok := rm.Load("key") // Iterate over all values rm.Range(func(key, value interface{}) bool { fmt.Printf("%v: %v\n", key, value) return true }) } ``` -------------------------------- ### Run GoIRCd Server Source: https://github.com/presbrey/pkg/blob/main/irc/README.md Instructions on how to run the GoIRCd server using the command line. This includes running with default configuration, a specific configuration file, or a remote configuration. ```bash # Run with default configuration (config.yaml) go run main.go # Run with a specific configuration file go run main.go -config /path/to/config.yaml # Run with a remote configuration go run main.go -config https://example.com/config.yaml ``` -------------------------------- ### Basic Hook Registry Usage in Go Source: https://github.com/presbrey/pkg/blob/main/hooks/README.md Demonstrates creating a new hook registry for a custom context type, registering a hook with default priority, and running all registered hooks. ```go import "github.com/presbrey/pkg/hooks" // Assuming MyContext is defined elsewhere type MyContext struct {} func main() { // Create a new hook registry for your context type registry := hooks.NewRegistry[*MyContext]() // Register a hook with default priority (0) registry.Register(func(ctx *MyContext) error { // Do something with the context return nil }) // Execute all registered hooks (all phases) context := &MyContext{} errors := registry.RunAll(context) // Check for errors if errors != nil { // Handle errors } } ``` -------------------------------- ### Testing Hook Registry Package Source: https://github.com/presbrey/pkg/blob/main/hooks/README.md Commands to run unit tests and benchmarks for the hook registry package. ```bash go test -v go test -bench=. ``` -------------------------------- ### Initialize and Use Feature Flags SDK with Echo Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Demonstrates how to initialize the feature flags SDK with configuration options like GitHub repository URL, caching, and fallback tenants. It also shows how to integrate the SDK into Echo handlers to check feature enablement and retrieve typed configuration values, including nested ones. ```go package main import ( "time" "github.com/labstack/echo/v4" "github.com/presbrey/pkg/echoflags" ) func main() { // Initialize the SDK sdk := echoflags.New(echoflags.Config{ GitHubRepoURL: "https://raw.githubusercontent.com/org/repo/main/tenants", CacheEnabled: true, CacheTTL: 5 * time.Minute, DefaultTenant: "default", FallbackTenant: "global", // Fallback to "global" tenant when keys not found }) // Create Echo app e := echo.New() // Use SDK in your handlers e.GET("/data", func(c echo.Context) error { // Set user in context (typically from authentication middleware) c.Set("user", "user@example.com") // Check if feature is enabled if sdk.IsEnabled(c, "feature1") { // Feature is enabled } // Get typed values (will fallback to "global" tenant if not found) maxItems, _ := sdk.GetInt(c, "maxItems") discount, _ := sdk.GetFloat64(c, "discount") regions, _ := sdk.GetStringSlice(c, "allowedRegions") // Access nested configuration version, _ := sdk.GetBoolByPath(c, "metadata.features.newDashboard") return c.JSON(200, map[string]interface{}{ "maxItems": maxItems, "discount": discount, "regions": regions, "newDashboard": version, }) }) e.Start(":8080") } ``` -------------------------------- ### Generate UUID-Based Slug Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a slug based on a UUID. ```bash slug -u # Output: _oc5-3bj0t9tqgmq1kidkq ``` -------------------------------- ### Generate Text-Based Slug Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a standard URL-safe slug from input text. ```bash slug "Hello World Example" # Output: hello-world-example ``` -------------------------------- ### Add Prefix and Suffix to Slug Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of adding a prefix and suffix to the generated slug. ```bash slug -p "prefix" -x "suffix" "Hello World" # Output: prefix-hello-world-suffix ``` -------------------------------- ### Generate Random Slug with Custom Length Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a random slug with a specified length. ```bash slug -r -e 12 # Output: a random 12-character slug ``` -------------------------------- ### Generate Slug with Custom Delimiter Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a slug using a custom character as a word separator. ```bash slug -d "_" "Hello World Example" # Output: hello_world_example ``` -------------------------------- ### Remove Stop Words from Slug Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a slug after removing common stop words from the input text. ```bash slug -s "The quick brown fox jumps over the lazy dog" # Output: quick-brown-fox-jumps-over-lazy-dog ``` -------------------------------- ### Priority-Based Hook Execution in Go Source: https://github.com/presbrey/pkg/blob/main/hooks/README.md Shows how to register hooks with different priorities and execute them by phase (Early, Middle, Late) or all together. ```go import "github.com/presbrey/pkg/hooks" // Assuming MyContext is defined elsewhere type MyContext struct {} func main() { registry := hooks.NewRegistry[*MyContext]() context := &MyContext{} // Register hooks with different priorities // Lower values run first (like Unix nice) // High priority (runs first, Early phase) registry.RegisterWithPriority(func(ctx *MyContext) error { // This runs first return nil }, -10) // Normal priority (Middle phase) registry.Register(func(ctx *MyContext) error { // This runs in the middle return nil }) // Low priority (runs last, Late phase) registry.RegisterWithPriority(func(ctx *MyContext) error { // This runs last return nil }, 10) // Run only Early hooks errsEarly := registry.RunEarly(context) // Run only Middle hooks errsMiddle := registry.RunMiddle(context) // Run only Late hooks errsLate := registry.RunLate(context) // Run all hooks in order (Early, Middle, Late) errsAll := registry.RunAll(context) } ``` -------------------------------- ### Add Custom Stop Words to Slug Generation Source: https://github.com/presbrey/pkg/blob/main/slugs/slugger/README.md Example of generating a slug while removing both common and custom specified stop words. ```bash slug -s -w "quick,brown,fox" "The quick brown fox jumps over the lazy dog" # Output: jumps-over-lazy-dog ``` -------------------------------- ### Go: Tenant-Specific Configuration with Fallback Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Demonstrates how to retrieve integer and boolean configuration values specific to a tenant, with a fallback to global defaults if the tenant-specific value is not found. Supports nested configuration access using dot notation. ```go import "github.com/labstack/echo/v4" import "your_sdk_path" // Example: tenant-specific configuration with global defaults func getTenantLimits(c echo.Context) (int, int) { // These will check tenant-specific config first, then fallback to "global" tenant maxUsers := sdk.GetIntWithDefault(c, "maxUsers", 100) maxStorage := sdk.GetIntWithDefault(c, "maxStorageGB", 10) return maxUsers, maxStorage } // Nested configuration access func getFeatureConfig(c echo.Context) map[string]bool { features := make(map[string]bool) // Access nested configuration with fallback using dot notation features["dashboard"] = sdk.GetBoolWithDefault(c, "features.dashboard", false) features["analytics"] = sdk.GetBoolWithDefault(c, "features.analytics", false) features["api"] = sdk.GetBoolWithDefault(c, "features.api", false) return features } ``` -------------------------------- ### Environment Variable Configuration Source: https://github.com/presbrey/pkg/blob/main/irc/README.md Examples of how to override GoIRCd configuration options using environment variables, following the `IRCD_SECTION_KEY=value` format. ```bash IRCD_SERVER_NAME=irc.example.com IRCD_SERVER_PORT=6667 IRCD_TLS_ENABLED=true ``` -------------------------------- ### Syncthing: Retrieving All Keys Source: https://github.com/presbrey/pkg/blob/main/syncthing/README.md Demonstrates how to retrieve a slice of all keys currently present in the synchronized map. ```Go keys := rm.Keys() fmt.Println("All keys:", keys) ``` -------------------------------- ### Bash: Running Tests and Coverage Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Provides commands to execute the Go test suite, including running tests with verbose output and generating code coverage reports. ```bash # Run the test suite go test -v ./... # Run with coverage go test -cover -coverprofile=coverage.out ./... go tool cover -html=coverage.out ``` -------------------------------- ### Go: Error Handling Strategies Source: https://github.com/presbrey/pkg/blob/main/echoflags/README.md Illustrates two primary methods for handling configuration retrieval errors in Go: explicit error checking and using SDK methods that provide default values, with the latter being the recommended approach. ```go import ( "strings" "your_sdk_path" "github.com/labstack/echo/v4" "log" ) // Method 1: Handle errors explicitly func getConfigWithErrorHandling(c echo.Context) interface{} { value, err := sdk.GetString(c, "key") if err != nil { if strings.Contains(err.Error(), "not found") { // Key doesn't exist in primary or fallback tenant return "defaultValue" } // Handle other errors (network, JSON parsing, etc.) log.Printf("Error getting feature flag: %v", err) return "defaultValue" } return value } // Method 2: Use methods with default values (recommended) func getConfigWithDefault(c echo.Context) (string, bool) { value := sdk.GetStringWithDefault(c, "key", "defaultValue") enabled := sdk.GetBoolWithDefault(c, "feature", false) return value, enabled } ``` -------------------------------- ### Advanced Priority Filtering for Hooks in Go Source: https://github.com/presbrey/pkg/blob/main/hooks/README.md Illustrates advanced methods for executing hooks based on specific priority ranges, less than, greater than, or exact priority levels. ```go import "github.com/presbrey/pkg/hooks" // Assuming MyContext is defined elsewhere type MyContext struct {} func main() { registry := hooks.NewRegistry[*MyContext]() context := &MyContext{} // Run hooks with priority within a specific range (inclusive) // For example, run hooks with priority between -5 and 5 errsRange := registry.RunPriorityRange(context, -5, 5) // Run hooks with priority strictly less than a value // For example, run hooks with priority less than 0 (equivalent to RunEarly) errsLessThan := registry.RunPriorityLessThan(context, 0) // Run hooks with priority strictly greater than a value // For example, run hooks with priority greater than 0 (equivalent to RunLate) errsGreaterThan := registry.RunPriorityGreaterThan(context, 0) // Run hooks with a specific priority level // For example, run hooks with priority exactly 0 (equivalent to RunMiddle) errsLevel := registry.RunLevel(context, 0) } ```