### Running CQRS Example Applications - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/cqrs/README.md This snippet provides shell commands to navigate to the distributed examples directory, start necessary infrastructure services like Redis using Docker, and execute the example applications included with the `gokit/cqrs` package. ```bash cd cqrs/examples/distributed make docker # Start Redis make all # Run all examples ``` -------------------------------- ### Setting Up CQRS Command Handling - Go Source: https://github.com/dmitrymomot/gokit/blob/main/cqrs/README.md This comprehensive snippet demonstrates the basic setup for command handling in the `gokit/cqrs` package. It involves defining a command struct, creating a command handler function, initializing a message publisher (using Redis as an example), setting up a command bus, configuring a command processor with an error handler, and starting the processor. ```go import ( "context" "log/slog" "github.com/dmitrymomot/gokit/cqrs" ) // 1. Define your command type CreateUserCommand struct { Name string `json:"name"` Email string `json:"email"` } // 2. Create a command handler handler := cqrs.NewCommandHandler(func(ctx context.Context, cmd *CreateUserCommand) error { // Handle the command - create user, validate, etc. return nil }) // 3. Set up the command bus redisClient := getRedisClient() // Your Redis client logger := slog.Default() publisher, err := cqrs.NewRedisPublisher(redisClient, logger) if err != nil { // Handle error } commandBus, err := cqrs.NewCommandBus(publisher, logger) if err != nil { // Handle error } // 4. Set up command processor errorHandler := func(ctx context.Context, err error) error { logger.ErrorContext(ctx, "Command processing error", "error", err) return nil } // Start in a goroutine or error group go cqrs.CommandProcessorFunc( ctx, cqrs.CommandProcessorConfig{ Logger: logger, SubscriberConstructor: cqrs.NewRedisSubscriber(redisClient, logger), ErrorHandler: errorHandler, }, handler, )() ``` -------------------------------- ### Installing gokit/async Go Package Source: https://github.com/dmitrymomot/gokit/blob/main/async/README.md Provides the command-line instruction to download and install the `async` package using the Go module system. This command fetches the package from its GitHub repository. Requires a Go environment setup with Go modules enabled. ```bash go get github.com/dmitrymomot/gokit/async ``` -------------------------------- ### Installing Go Pagination Package Source: https://github.com/dmitrymomot/gokit/blob/main/pagination/README.md This snippet shows the standard Go command to download and install the pagination package using `go get`. It is the required first step to use the package in a Go project. ```bash go get github.com/dmitrymomot/gokit/pagination ``` -------------------------------- ### Installing gokit/utils Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/utils/README.md Provides the command line instruction to install the `gokit/utils` Go package using the `go get` tool. This is the standard method for fetching and installing Go modules from a remote repository. ```Bash go get github.com/dmitrymomot/gokit/utils ``` -------------------------------- ### Basic RBAC Setup and Permission Checking - Go Source: https://github.com/dmitrymomot/gokit/blob/main/rbac/README.md This comprehensive example demonstrates the basic setup of the RBAC service using an in-memory store. It shows how to define permissions and roles with inheritance, store them, and check if a role has a specific permission, illustrating inheritance effects. ```go import ( "context" "fmt" "github.com/dmitrymomot/gokit/rbac" ) func main() { // Create a context and in-memory store ctx := context.Background() store := rbac.NewMemoryStore() rbacService := rbac.NewService(store) // Define workspace ID workspaceID := "organization-123" // Create permissions with inheritance viewPerm := rbac.Permission{ WorkspaceID: workspaceID, ID: "post:read", Name: "Can read posts", } writePerm := rbac.Permission{ WorkspaceID: workspaceID, ID: "post:write", Name: "Can write posts", ParentIDs: []string{"post:read"}, // Writing includes reading } deletePerm := rbac.Permission{ WorkspaceID: workspaceID, ID: "post:delete", Name: "Can delete posts", ParentIDs: []string{"post:write"}, // Deleting includes writing } // Store the permissions store.CreatePermission(ctx, viewPerm) store.CreatePermission(ctx, writePerm) store.CreatePermission(ctx, deletePerm) // Create roles with inheritance guestRole := rbac.Role{ WorkspaceID: workspaceID, ID: "guest", Name: "Guest User", DirectPermissionIDs: []string{"post:read"}, } editorRole := rbac.Role{ WorkspaceID: workspaceID, ID: "editor", Name: "Editor User", ParentIDs: []string{"guest"}, DirectPermissionIDs: []string{"post:write"}, } adminRole := rbac.Role{ WorkspaceID: workspaceID, ID: "admin", Name: "Admin User", ParentIDs: []string{"editor"}, DirectPermissionIDs: []string{"post:delete"}, } // Store the roles store.CreateRole(ctx, guestRole) store.CreateRole(ctx, editorRole) store.CreateRole(ctx, adminRole) // Check permissions hasPermission, _ := rbacService.HasPermission(ctx, workspaceID, "guest", "post:read") fmt.Printf("Guest has post:read: %v\n", hasPermission) // true hasPermission, _ = rbacService.HasPermission(ctx, workspaceID, "guest", "post:write") fmt.Printf("Guest has post:write: %v\n", hasPermission) // false hasPermission, _ = rbacService.HasPermission(ctx, workspaceID, "editor", "post:read") fmt.Printf("Editor has post:read: %v\n", hasPermission) // true (inherited from guest) hasPermission, _ = rbacService.HasPermission(ctx, workspaceID, "admin", "post:delete") fmt.Printf("Admin has post:delete: %v\n", hasPermission) // true } ``` -------------------------------- ### Installing API Key Package (Bash) Source: https://github.com/dmitrymomot/gokit/blob/main/apikey/README.md Installs the `apikey` Go package using the `go get` command. This command downloads the package source code and any dependencies from the specified GitHub repository, making it available for use in your Go projects. ```Bash go get github.com/dmitrymomot/gokit/apikey ``` -------------------------------- ### Setting Up CQRS Event Handling - Go Source: https://github.com/dmitrymomot/gokit/blob/main/cqrs/README.md This snippet outlines the setup for event handling, mirroring the command handling process. It involves defining an event struct, creating an event handler function, setting up an event bus (using the same publisher), and configuring and starting an event processor. ```go // 1. Define your event type UserCreatedEvent struct { UserID string `json:"user_id"` Name string `json:"name"` } // 2. Create an event handler eventHandler := cqrs.NewEventHandler(func(ctx context.Context, event *UserCreatedEvent) error { // React to the event - send email, update projections, etc. return nil }) // 3. Set up the event bus eventBus, err := cqrs.NewEventBus(publisher, logger) if err != nil { // Handle error } // 4. Set up event processor go cqrs.EventProcessorFunc( ctx, cqrs.EventProcessorConfig{ Logger: logger, SubscriberConstructor: cqrs.NewRedisSubscriber(redisClient, logger), ErrorHandler: errorHandler, }, eventHandler, )() ``` -------------------------------- ### Installing gokit/cqrs package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/cqrs/README.md This snippet shows the standard Go command to fetch and install the `github.com/dmitrymomot/gokit/cqrs` package, making it available for use in your Go projects. ```bash go get github.com/dmitrymomot/gokit/cqrs ``` -------------------------------- ### Installing Go State Machine Package (bash) Source: https://github.com/dmitrymomot/gokit/blob/main/statemachine/README.md Provides the command line instruction to download and install the `statemachine` package using the standard Go package manager. Requires a Go environment with `go` command installed. ```bash go get github.com/dmitrymomot/gokit/statemachine ``` -------------------------------- ### Installing OpenSearch Go Package (Bash) Source: https://github.com/dmitrymomot/gokit/blob/main/opensearch/README.md Provides the command line instruction using `go get` to download and install the `opensearch` package from the gokit repository. This command is necessary to include the package in your Go project's dependencies. ```bash go get github.com/dmitrymomot/gokit/opensearch ``` -------------------------------- ### Install GoKit Package (Shell) Source: https://github.com/dmitrymomot/gokit/blob/main/README.md Uses the Go package manager (`go get`) to download and install the GoKit library and its dependencies from the specified GitHub repository. This command is the standard way to add GoKit to your project. ```sh go get github.com/dmitrymomot/gokit ``` -------------------------------- ### Basic Feature Flag Setup and Check Go Source: https://github.com/dmitrymomot/gokit/blob/main/feature/README.md This Go code demonstrates initializing an in-memory feature flag provider with example flags and checking the status of a flag using `IsEnabled`. It shows how to define simple boolean flags and flags with basic strategies. ```go package main import ( "context" "log" "github.com/dmitrymomot/gokit/feature" ) func main() { // Create a provider with initial flags provider, err := feature.NewMemoryProvider( &feature.Flag{ Name: "dark-mode", Description: "Enable dark mode UI", Enabled: true, Tags: []string{"ui", "theme"}, }, &feature.Flag{ Name: "beta-features", Description: "Enable beta features", Enabled: true, Strategy: feature.NewTargetedStrategy(feature.TargetCriteria{ Groups: []string{"beta-users", "internal"}, }), }, ) if err != nil { log.Fatalf("Failed to create feature provider: %v", err) } defer provider.Close() // Check if a feature is enabled ctx := context.Background() darkModeEnabled, err := provider.IsEnabled(ctx, "dark-mode") if err != nil { log.Printf("Error checking flag: %v", err) } if darkModeEnabled { // Enable dark mode UI log.Println("Dark mode is enabled!") } } ``` -------------------------------- ### Installing GoKit Config Package Bash Source: https://github.com/dmitrymomot/gokit/blob/main/config/README.md This snippet provides the standard Go command to download and install the `gokit/config` package from its GitHub repository. This is the necessary first step before using the package in a Go project. ```Bash go get github.com/dmitrymomot/gokit/config ``` -------------------------------- ### Installing GoKit pg Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/pg/README.md Provides the standard Go command to install the `dmitrymomot/gokit/pg` package and its dependencies. This is the first step to using the package in a Go project. ```Bash go get github.com/dmitrymomot/gokit/pg ``` -------------------------------- ### API Reference - Message Bus Initialization - Go Source: https://github.com/dmitrymomot/gokit/blob/main/sse/README.md This Go snippet provides examples for initializing the available message bus implementations: `bus.NewChannelBus()` for single-server in-memory use and `bus.NewRedisBus` or `bus.NewRedisBusWithConfig` for distributed setups using Redis. ```go // In-memory (single server) bus := bus.NewChannelBus() // Redis-backed (distributed) bus, err := bus.NewRedisBus(redisClient) // or with custom buffer size: bus, err := bus.NewRedisBusWithConfig(redisClient, 200) ``` -------------------------------- ### Installing Go QR Code Package Source: https://github.com/dmitrymomot/gokit/blob/main/qrcode/README.md This command uses the Go toolchain to download and install the `gokit/qrcode` package from its GitHub repository. ```bash go get github.com/dmitrymomot/gokit/qrcode ``` -------------------------------- ### Installing gokit/sse package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/sse/README.md This command installs the `sse` package and its dependencies from the `dmitrymomot/gokit` repository using the Go module system. ```bash go get github.com/dmitrymomot/gokit/sse ``` -------------------------------- ### Installing Randomname Package Bash Source: https://github.com/dmitrymomot/gokit/blob/main/randomname/README.md Command to fetch and install the `randomname` Go package using the `go get` tool. This adds the package to your Go workspace. ```Bash go get github.com/dmitrymomot/gokit/randomname ``` -------------------------------- ### Installing Go Semantic Versioning Package Source: https://github.com/dmitrymomot/gokit/blob/main/semver/README.md Use the Go package manager to download and install the `semver` package into your Go modules. ```bash go get github.com/dmitrymomot/gokit/semver ``` -------------------------------- ### Installing Go Kit Sanitizer Package Source: https://github.com/dmitrymomot/gokit/blob/main/sanitizer/README.md Provides the command-line instruction to download and install the Go Kit 'sanitizer' package using the standard Go module system. This is the required first step before using the package in a Go project. ```Bash go get github.com/dmitrymomot/gokit/sanitizer ``` -------------------------------- ### Installing GoKit Webhook Package Source: https://github.com/dmitrymomot/gokit/blob/main/webhook/README.md This snippet provides the command to install the `gokit/webhook` package using Go modules. It fetches the package and its dependencies from the specified Git repository. ```bash go get github.com/dmitrymomot/gokit/webhook ``` -------------------------------- ### Installing Google OAuth Go Package Source: https://github.com/dmitrymomot/gokit/blob/main/oauth/google/README.md This command installs the Go Google OAuth 2.0 client package using the Go module system. It fetches the package and its dependencies from the specified GitHub repository. ```bash go get github.com/dmitrymomot/gokit/oauth/google ``` -------------------------------- ### Installing TOTP Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/totp/README.md Provides the command line instruction to install the `github.com/dmitrymomot/gokit/totp` package using the Go module system. This command fetches the latest version of the package and its dependencies. ```bash go get github.com/dmitrymomot/gokit/totp ``` -------------------------------- ### Install Go Cache Package Source: https://github.com/dmitrymomot/gokit/blob/main/cache/README.md This command uses the Go module system to download and install the cache package. ```bash go get github.com/dmitrymomot/gokit/cache ``` -------------------------------- ### Installing Go Scopes Package Source: https://github.com/dmitrymomot/gokit/blob/main/scopes/README.md This snippet shows the command-line instruction to install the 'scopes' package from the gokit repository using the standard Go module installation tool. ```bash go get github.com/dmitrymomot/gokit/scopes ``` -------------------------------- ### Installing GoKit Storage Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/storage/README.md Command to fetch and install the `gokit/storage` Go package using the standard Go module system. This command downloads the package and its dependencies into your Go workspace. ```Bash go get github.com/dmitrymomot/gokit/storage ``` -------------------------------- ### Setup GoKit Development Git Hooks (Shell) Source: https://github.com/dmitrymomot/gokit/blob/main/README.md Executes a shell script located in the `./scripts` directory to install client-side Git hooks specific to the GoKit repository's development workflow. These hooks automate checks like formatting and testing before pushing commits. ```sh ./scripts/setup-git-hooks.sh ``` -------------------------------- ### Loading Database Configuration in Go Source: https://github.com/dmitrymomot/gokit/blob/main/config/README.md This example demonstrates how to define a configuration struct using `env` tags and load it using `config.Load`. It shows how to specify environment variable names, default values, and required fields, including basic error handling for the loading process. ```Go package main import ( "fmt" "log" "github.com/dmitrymomot/gokit/config" ) type DatabaseConfig struct { Host string `env:"DB_HOST" envDefault:"localhost"` Port int `env:"DB_PORT" envDefault:"5432"` Username string `env:"DB_USER,required"` Password string `env:"DB_PASS,required"` } func main() { // Load the configuration dbConfig, err := config.Load[DatabaseConfig]() if err != nil { log.Fatalf("Failed to load config: %v", err) } // Use the configuration fmt.Printf("Database connection: %s:%d\n", dbConfig.Host, dbConfig.Port) } ``` -------------------------------- ### Installing gokit/logger Go Package Source: https://github.com/dmitrymomot/gokit/blob/main/logger/README.md Command to download and install the `gokit/logger` package using Go modules. This is the required first step to use the library within your Go project. ```bash go get github.com/dmitrymomot/gokit/logger ``` -------------------------------- ### Installing MongoDB Go Kit Package (Bash) Source: https://github.com/dmitrymomot/gokit/blob/main/mongo/README.md Command to install the `mongo` package from the `dmitrymomot/gokit` repository using the Go module system. This fetches the package and its dependencies for use in a Go project. ```Bash go get github.com/dmitrymomot/gokit/mongo ``` -------------------------------- ### Install Go Mailer Package Bash Source: https://github.com/dmitrymomot/gokit/blob/main/mailer/README.md Installs the gokit mailer package using the standard Go package manager. This command fetches the package and its dependencies from the specified GitHub repository. ```bash go get github.com/dmitrymomot/gokit/mailer ``` -------------------------------- ### Initialize and Use Redis Cache in Go Source: https://github.com/dmitrymomot/gokit/blob/main/cache/README.md Demonstrates how to create a Redis client, wrap it with the `NewRedisAdapter`, and perform basic cache operations like `Set` and `Get`. Requires a running Redis server and the `github.com/redis/go-redis/v9` dependency. ```go import ( "context" "time" "github.com/dmitrymomot/gokit/cache" "github.com/redis/go-redis/v9" ) // Create a Redis client redisClient := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) // Create a Redis cache adapter redisCache, err := cache.NewRedisAdapter(redisClient) if err != nil { // Handle error } defer redisCache.Close() ctx := context.Background() // Use the cache err = redisCache.Set(ctx, "user:123", []byte(`{"name":"John"}`), time.Hour) value, found, err := redisCache.Get(ctx, "user:123") ``` -------------------------------- ### Installing GoKit Binder Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/binder/README.md Command to download and install the GoKit binder package using the Go module system. This command adds the package as a dependency to your Go project. ```Bash go get github.com/dmitrymomot/gokit/binder ``` -------------------------------- ### Installing GoKit Token Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/token/README.md Command to fetch and install the `gokit/token` package using the Go module system. This command adds the package dependency to your Go project. ```Bash go get github.com/dmitrymomot/gokit/token ``` -------------------------------- ### Installing gokit JWT package Source: https://github.com/dmitrymomot/gokit/blob/main/jwt/README.md This snippet provides the command line instruction to install the `gokit/jwt` package using the Go module system. It fetches the package and its dependencies from the specified GitHub repository. ```bash go get github.com/dmitrymomot/gokit/jwt ``` -------------------------------- ### API Reference - Server Methods and Options - Go Source: https://github.com/dmitrymomot/gokit/blob/main/sse/README.md This Go snippet provides a reference for common methods and options available on the `sse.Server` object. It shows how to create a new server, apply options like heartbeat and hostname, get an HTTP handler for connections, publish events, and close the server. ```go // Create a new SSE server server := sse.NewServer(messageBus, [options...]) // Available options sse.WithHeartbeat(duration) // Set heartbeat interval (default: 30s) sse.WithHostname(hostname) // Set hostname for event IDs // Get an HTTP handler for SSE connections handler := server.Handler(topicExtractorFunc) // Publish an event to a topic err := server.Publish(ctx, topic, event) // Close the server err := server.Close() ``` -------------------------------- ### Install Go i18n Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/i18n/README.md Provides the command-line instruction to download and install the `i18n` package using the standard Go module system. This command adds the package as a dependency to your current Go project. ```Bash go get github.com/dmitrymomot/gokit/i18n ``` -------------------------------- ### Using SemVer for API Versioning in Go Source: https://github.com/dmitrymomot/gokit/blob/main/semver/README.md Provides examples of how to use the `semver` package to check client version compatibility against minimum required versions or supported version ranges for APIs, demonstrating practical application of comparison methods. ```Go // API versioning with constraints apiMinVersion := semver.MustParse("2.0.0") clientVersion := semver.MustParse("2.1.3") if clientVersion.LessThan(apiMinVersion) { return errors.New("client version too old, please upgrade") } // Check compatibility with a version range minSupported := semver.MustParse("1.5.0") maxSupported := semver.MustParse("3.0.0") if !clientVersion.InRange(minSupported, maxSupported) { return errors.New("unsupported client version") } ``` -------------------------------- ### Install Go Feature Flagging Package Source: https://github.com/dmitrymomot/gokit/blob/main/feature/README.md This snippet provides the command to install the gokit feature flagging package using the Go module system. ```bash go get github.com/dmitrymomot/gokit/feature ``` -------------------------------- ### Installing GoKit Privacy Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/privacy/README.md Provides the command-line instruction to download and install the `privacy` package using the Go module system. This is the first step required to include and use the library in a Go project. ```bash go get github.com/dmitrymomot/gokit/privacy ``` -------------------------------- ### Installing Go User-Agent Package (Bash) Source: https://github.com/dmitrymomot/gokit/blob/main/useragent/README.md Provides the command-line instruction to download and add the `useragent` package to your Go project's dependencies using the Go module system. ```bash go get github.com/dmitrymomot/gokit/useragent ``` -------------------------------- ### Installing GoKit RBAC Package - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/rbac/README.md This snippet provides the command to install the gokit/rbac package using the Go module system. It fetches the latest version of the package and adds it to your project's dependencies. ```bash go get github.com/dmitrymomot/gokit/rbac ``` -------------------------------- ### Installing GoKit HTTP Middlewares - Bash Source: https://github.com/dmitrymomot/gokit/blob/main/router/middlewares/README.md This Bash command uses the Go module system to download and install the `middlewares` package from the `gokit` repository. It's the standard way to add this dependency to a Go project. ```Bash go get github.com/dmitrymomot/gokit/router/middlewares ``` -------------------------------- ### Creating CQRS Message Publishers - Go Source: https://github.com/dmitrymomot/gokit/blob/main/cqrs/README.md This snippet provides examples of how to initialize different message publisher implementations supported by the `gokit/cqrs` package, including Redis, Kafka, In-memory (Go channels), and PostgreSQL. These publishers are used to send commands and publish events. ```go // Redis publisher (recommended for production) redisPublisher, err := cqrs.NewRedisPublisher(redisClient, logger) // Kafka publisher kafkaPublisher, err := cqrs.NewKafkaPublisher([]string{"localhost:9092"}, logger) // In-memory publisher (for testing) goChannelPublisher := cqrs.NewGoChannelPublisher(logger) // PostgreSQL publisher (for delayed processing) pgPublisher, err := cqrs.NewPostgresPublisher(db, logger) ``` -------------------------------- ### Initialize and Use LRU Cache in Go Source: https://github.com/dmitrymomot/gokit/blob/main/cache/README.md Shows how to create an in-memory LRU cache adapter with a specified capacity using `NewLRUAdapter`. It demonstrates performing standard cache `Set` and `Get` operations using the generic `Cache` interface. ```go // Create an in-memory LRU cache with capacity of 1000 items lruCache, err := cache.NewLRUAdapter(1000) if err != nil { // Handle error } // Use the cache (same API as Redis cache) err = lruCache.Set(ctx, "session:xyz", []byte("session-data"), 5*time.Minute) value, found, err := lruCache.Get(ctx, "session:xyz") ``` -------------------------------- ### Initialize Translator and Get Basic Translations - Go Source: https://github.com/dmitrymomot/gokit/blob/main/i18n/README.md Shows how to create a new `Translator` instance, typically requiring a `TranslationAdapter` for loading translations, and configure it with options like default language and fallback behavior. It then demonstrates using the basic `T` method to retrieve translations for a given key in different languages. ```Go import ( "context" "fmt" "github.com/dmitrymomot/gokit/i18n" ) // Initialize translator translator, err := i18n.NewTranslator(context.Background(), adapter, i18n.WithDefaultLanguage("en"), i18n.WithFallbackToKey(true), ) if err != nil { // Handle initialization error } // Get translation in default language greeting, err := translator.T("en", "greeting") if err != nil { // Handle translation error } fmt.Println(greeting) // "Hello, world!" // Get translation in specific language frGreeting := translator.T("fr", "greeting") fmt.Println(frGreeting) // "Bonjour, le monde!" ``` -------------------------------- ### Initializing OpenSearch Client with Direct Config (Go) Source: https://github.com/dmitrymomot/gokit/blob/main/opensearch/README.md Demonstrates how to create a new OpenSearch client instance by providing a configuration struct directly with addresses and credentials. Requires the `context` package for the operation context and the `github.com/dmitrymomot/gokit/opensearch` package. ```Go import ( "context" "github.com/dmitrymomot/gokit/opensearch" ) // Create an OpenSearch client with direct configuration client, err := opensearch.New(context.Background(), opensearch.Config{ Addresses: []string{"https://localhost:9200"}, Username: "admin", Password: "admin", }) if err != nil { // Handle error } // Use the client info, err := client.Info() ``` -------------------------------- ### Sending GET Request with Query Parameters in Go Source: https://github.com/dmitrymomot/gokit/blob/main/webhook/README.md This example demonstrates sending a GET request using the webhook sender. It shows that parameters provided as a map are automatically converted into query string parameters for GET requests, forming the final URL. ```go // Parameters are automatically converted to query string for GET requests // This will make a request to: https://api.example.com/search?term=golang&limit=10 params := map[string]any{ "term": "golang", "limit": 10, } resp, err := sender.Send( ctx, "https://api.example.com/search", params, webhook.WithMethod("GET"), ) ``` -------------------------------- ### Creating Basic MongoDB Client (Go) Source: https://github.com/dmitrymomot/gokit/blob/main/mongo/README.md Demonstrates how to create a MongoDB client instance using a direct configuration struct. It shows importing necessary packages, initializing the client with a connection URL, handling potential errors, and deferring the connection disconnect. It also shows how to access a database and collection. ```Go import ( "context" "log" "github.com/dmitrymomot/gokit/mongo" ) // Create a MongoDB client with direct configuration client, err := mongo.New(context.Background(), mongo.Config{ ConnectionURL: "mongodb://localhost:27017", }) if err != nil { log.Fatalf("Failed to connect: %v", err) } defer client.Disconnect(context.Background()) // Use the client collection := client.Database("mydb").Collection("mycollection") ``` -------------------------------- ### Go State Machine Interface Methods Reference Source: https://github.com/dmitrymomot/gokit/blob/main/statemachine/README.md Describes the main methods provided by the `StateMachine` interface, including getting the current state, adding transitions, triggering events, checking if an event can be fired, and resetting the machine to its initial state. Requires understanding Go interfaces. ```Go // StateMachine interface - core API type StateMachine interface { // Returns the current state Current() State // Adds a new transition AddTransition(from, to State, event Event, guards []Guard, actions []Action) error // Triggers an event, potentially causing a state transition Fire(ctx context.Context, event Event, data any) error // Checks if an event can be fired in the current state CanFire(ctx context.Context, event Event, data any) bool // Resets to initial state Reset() error } ``` -------------------------------- ### Handling Logger Creation Errors in Go Source: https://github.com/dmitrymomot/gokit/blob/main/logger/README.md Provides a basic example of how to handle potential errors that might occur during the creation of a logger instance, such as configuration validation failures. It shows the standard Go pattern of checking the returned error and taking appropriate action. ```go // Config validation errors are returned when creating loggers log, err := createLogger() if err != nil { // Handle error } // Runtime logging errors are typically handled internally // If needed, you can implement your own error handling in custom handlers ``` -------------------------------- ### Generating and Encrypting TOTP Secrets - Go Source: https://github.com/dmitrymomot/gokit/blob/main/totp/README.md Demonstrates the initial setup process, including generating a secure encryption key (for storing secrets), generating a user-specific TOTP secret, and encrypting that secret using the generated key before storing it. Requires the `encoding/base64` and `gokit/totp` packages. ```go import ( "encoding/base64" "github.com/dmitrymomot/gokit/totp" ) // Generate a new encryption key (store this securely) key, err := totp.GenerateEncryptionKey() if err != nil { // Handle error } encodedKey := base64.StdEncoding.EncodeToString(key) // Save this key securely (environment variable, key vault, etc.) // Generate a new TOTP secret for a user secret, err := totp.GenerateSecretKey() if err != nil { // Handle error } // Encrypt the secret before storage encryptedSecret, err := totp.EncryptSecret(secret, key) if err != nil { // Handle error } // Store encryptedSecret in your database ``` -------------------------------- ### Initializing OpenSearch Client with Environment Config (Go) Source: https://github.com/dmitrymomot/gokit/blob/main/opensearch/README.md Illustrates creating an OpenSearch client by loading configuration from environment variables using the `gokit/config` package. This method is recommended for production environments to externalize configuration. Requires `github.com/dmitrymomot/gokit/config` and `github.com/dmitrymomot/gokit/opensearch`. ```Go import ( "github.com/dmitrymomot/gokit/config" "github.com/dmitrymomot/gokit/opensearch" ) // Load OpenSearch config from environment variables cfg, err := config.Load[opensearch.Config]() if err != nil { // Handle error } // Create client with loaded config client, err := opensearch.New(context.Background(), cfg) ``` -------------------------------- ### Initializing Storage Client with Pre-configured S3 Client - Go Source: https://github.com/dmitrymomot/gokit/blob/main/storage/README.md Shows how to inject a pre-configured AWS SDK v2 S3 client into the gokit storage client initialization using the `storage.WithS3Client` functional option. This allows for fine-grained control over the underlying S3 client configuration based on existing AWS SDK setup. ```Go // Using with pre-configured S3 client customS3Client := s3.NewFromConfig(awsConfig) client, err := storage.New( ctx, cfg, storage.WithS3Client(customS3Client), ) ``` -------------------------------- ### Sending Basic Webhook Request in Go Source: https://github.com/dmitrymomot/gokit/blob/main/webhook/README.md This example demonstrates the basic usage of the webhook sender to send a POST request with a JSON payload. It shows how to initialize the sender, create a context, define request parameters as a map, send the request, and handle potential errors and check the response status. ```go import ( "context" "fmt" "github.com/dmitrymomot/gokit/webhook" "time" ) func main() { // Create a new webhook sender sender := webhook.NewWebhookSender() // Create a context ctx := context.Background() // Send a POST request with JSON payload params := map[string]any{ "event": "user.created", "user_id": 123456, "timestamp": time.Now().Unix(), } // Send the webhook request resp, err := sender.Send(ctx, "https://api.example.com/webhook", params) if err != nil { // Handle error facade.Log.Errorf("Failed to send webhook: %v", err) return } // Check response status if !resp.IsSuccessful() { facade.Log.Errorf("Request failed with status %d: %s", resp.StatusCode, resp.Body) return } facade.Log.Info("Webhook sent successfully!") } ``` -------------------------------- ### Initializing Storage Client with Basic Config - Go Source: https://github.com/dmitrymomot/gokit/blob/main/storage/README.md Demonstrates how to create a new storage client instance using the `storage.New` function with a basic configuration struct. It requires AWS/S3 credentials, region, bucket, endpoint (optional), and sets a maximum file size limit. Proper error handling after initialization is crucial. ```Go import ( "context" "github.com/dmitrymomot/gokit/storage" ) func main() { cfg := storage.Config{ Key: "your-access-key", Secret: "your-secret-key", Region: "us-west-1", Bucket: "your-bucket", Endpoint: "https://s3.amazonaws.com", MaxFileSize: 10 * 1024 * 1024, // 10MB } ctx := context.Background() client, err := storage.New(ctx, cfg) if err != nil { // Handle error } // Use the client } ``` -------------------------------- ### Installing gokit/validator Go Package Source: https://github.com/dmitrymomot/gokit/blob/main/validator/README.md This command installs the gokit/validator package using the Go module system. It fetches the latest version of the library from its repository. ```bash go get github.com/dmitrymomot/gokit/validator ``` -------------------------------- ### Create Mailer Client and Send Simple Email Go Source: https://github.com/dmitrymomot/gokit/blob/main/mailer/README.md Demonstrates creating a mailer client with explicit configuration and sending a basic HTML email using the SendEmail method. Requires a context.Context object and the mailer package. Handles potential errors during client creation. ```go import ( "context" "github.com/dmitrymomot/gokit/mailer" ) // Create a mailer client client, err := mailer.NewClient(mailer.Config{ PostmarkServerToken: "your-postmark-server-token", PostmarkAccountToken: "your-postmark-account-token", SenderEmail: "noreply@example.com", SupportEmail: "support@example.com", }) if err != nil { // Handle error } // Send a simple email err = client.SendEmail(context.Background(), mailer.SendEmailParams{ SendTo: "user@example.com", Subject: "Welcome!", BodyHTML: "
Welcome to our service!
", Tag: "welcome", }) ``` -------------------------------- ### Connecting with Environment Config - Go Source: https://github.com/dmitrymomot/gokit/blob/main/pg/README.md Illustrates loading PostgreSQL configuration from environment variables using `gokit/config.Load` and then connecting to the database using the loaded configuration. This promotes flexible deployment without hardcoding connection details. ```Go import ( "github.com/dmitrymomot/gokit/config" "github.com/dmitrymomot/gokit/pg" ) // Load PostgreSQL config from environment variables cfg, err := config.Load[pg.Config]() if err != nil { // Handle configuration error } // Connect with loaded config db, err := pg.Connect(context.Background(), cfg) ``` -------------------------------- ### Creating and Using Basic Go State Machine Source: https://github.com/dmitrymomot/gokit/blob/main/statemachine/README.md Illustrates the definition of string-based states and events, constructing a state machine using the fluent builder API, and triggering state transitions by firing events. Requires the `gokit/statemachine` package. ```Go import ( "context" "fmt" "github.com/dmitrymomot/gokit/statemachine" ) func main() { // Define states using string constants const ( Draft = statemachine.StringState("draft") InReview = statemachine.StringState("in_review") Approved = statemachine.StringState("approved") Published = statemachine.StringState("published") Rejected = statemachine.StringState("rejected") ) // Define events const ( Submit = statemachine.StringEvent("submit") Approve = statemachine.StringEvent("approve") Reject = statemachine.StringEvent("reject") Publish = statemachine.StringEvent("publish") Withdraw = statemachine.StringEvent("withdraw") ) // Create and configure the state machine using the fluent builder API builder := statemachine.NewBuilder(Draft) builder.From(Draft).When(Submit).To(InReview).Add() builder.From(InReview).When(Approve).To(Approved).Add() builder.From(InReview).When(Reject).To(Rejected).Add() builder.From(Approved).When(Publish).To(Published).Add() builder.From(Approved).When(Withdraw).To(Draft).Add() builder.From(Rejected).When(Submit).To(InReview).Add() machine := builder.Build() // Use the state machine ctx := context.Background() fmt.Printf("Current state: %s\n", machine.Current().Name()) // "draft" // Trigger transitions machine.Fire(ctx, Submit, nil) fmt.Printf("Current state: %s\n", machine.Current().Name()) // "in_review" machine.Fire(ctx, Approve, nil) fmt.Printf("Current state: %s\n", machine.Current().Name()) // "approved" } ``` -------------------------------- ### Creating Client with Env Config (Go) Source: https://github.com/dmitrymomot/gokit/blob/main/mongo/README.md Shows how to load MongoDB connection configuration from environment variables using the `gokit/config` package. It then uses the loaded `cfg` struct to create a new `mongo.Client` instance, providing a flexible way to configure the connection without hardcoding values. ```Go import ( "github.com/dmitrymomot/gokit/config" "github.com/dmitrymomot/gokit/mongo" ) // Load MongoDB config from environment variables cfg, err := config.Load[mongo.Config]() if err != nil { log.Fatalf("Failed to load config: %v", err) } // Create client with loaded config client, err := mongo.New(context.Background(), cfg) ``` -------------------------------- ### Connecting to PostgreSQL - Go Source: https://github.com/dmitrymomot/gokit/blob/main/pg/README.md Demonstrates how to establish a basic connection to a PostgreSQL database using the `pg.Connect` function with a context and a literal connection string configuration. It shows how to handle potential connection errors and ensures the connection is closed properly using `defer`. ```Go import ( "context" "github.com/dmitrymomot/gokit/pg" ) // Create a PostgreSQL connection db, err := pg.Connect(context.Background(), pg.Config{ ConnectionString: "postgres://user:password@localhost:5432/dbname", }) if err != nil { // Handle connection error } defer db.Close() // Use the connection // ... ``` -------------------------------- ### Connecting Directly to Database (Go) Source: https://github.com/dmitrymomot/gokit/blob/main/mongo/README.md Illustrates using the `mongo.NewWithDatabase` function to create a client and immediately return a `mongo.Database` instance for a specified database name. This is useful when the application primarily interacts with a single database. ```Go // Direct connection to a specific database db, err := mongo.NewWithDatabase(context.Background(), cfg, "mydb") if err != nil { log.Fatalf("Failed to connect to database: %v", err) } // Use the database collection := db.Collection("users") ``` -------------------------------- ### Loading Configuration with MustLoad in Go Source: https://github.com/dmitrymomot/gokit/blob/main/config/README.md This snippet demonstrates using `config.MustLoad` for loading configurations that are essential for application startup. Unlike `config.Load`, `MustLoad` will panic if it fails to load the configuration due to missing or invalid environment variables. ```Go // Will panic if environment variables are missing or invalid appConfig := config.MustLoad[AppConfig]() ``` -------------------------------- ### Getting Function and Struct Names via Reflection - Go Source: https://github.com/dmitrymomot/gokit/blob/main/utils/README.md Demonstrates the use of `utils.QualifiedFuncName` to obtain the full path and name of functions or methods, and `utils.GetStructName` to get the simple name of a struct type. These utilities are primarily intended for reflection-based tasks such as logging or debugging. ```Go // Get the fully qualified name of a function funcName := utils.QualifiedFuncName(myFunction) fmt.Println(funcName) // "github.com/myorg/mypackage.myFunction" // Works with method references too methodName := utils.QualifiedFuncName(myStruct.Method) fmt.Println(methodName) // "github.com/myorg/mypackage.MyStruct.Method" // Get struct names for logging and reflection type User struct { Name string Age int } structName := utils.GetStructName(User{}) fmt.Println(structName) // "User" // Works with pointers too structName = utils.GetStructName(&User{}) fmt.Println(structName) // "User" ``` -------------------------------- ### Running Database Migrations - Go Source: https://github.com/dmitrymomot/gokit/blob/main/pg/README.md Shows the process of connecting to the database and then applying schema migrations defined in a specified path using the `pg.Migrate` function. A logger is required for migration output. The configuration must include `MigrationsPath`. ```Go import ( "context" "log/slog" "github.com/dmitrymomot/gokit/pg" ) // Create logger (required for migrations) logger := slog.Default() // Connect to database db, err := pg.Connect(context.Background(), pg.Config{ ConnectionString: "postgres://user:password@localhost:5432/dbname", MigrationsPath: "./migrations", // Path to migration files }) if err != nil { // Handle error } defer db.Close() // Run migrations to latest version err = pg.Migrate(context.Background(), db, cfg, logger) if err != nil { // Handle migration error } ``` -------------------------------- ### Using Specific Binding Methods - Go Source: https://github.com/dmitrymomot/gokit/blob/main/binder/README.md Provides examples of calling the content-type specific binding functions (`BindJSON`, `BindForm`, `BindQuery`) directly to handle specific request formats, offering more control than the automatic `Bind` function. Each example includes basic error handling boilerplate. ```Go // JSON binding var jsonData User if err := binder.BindJSON(r, &jsonData); err != nil { // Handle error } ``` ```Go // Form data binding var formData User if err := binder.BindForm(r, &formData); err != nil { // Handle error } ``` ```Go // Query parameter binding var queryParams User if err := binder.BindQuery(r, &queryParams); err != nil { // Handle error } ``` -------------------------------- ### Connecting to Redis - GoKit Redis (Go) Source: https://github.com/dmitrymomot/gokit/blob/main/redis/README.md Demonstrates establishing a basic connection to Redis using a hardcoded connection URL and other configuration options provided by the gokit/redis package. It shows how to use a context with timeout and perform a simple Set operation. ```go import ( "context" "github.com/dmitrymomot/gokit/redis" ) func main() { // Create a context with timeout ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() // Connect with configuration client, err := redis.Connect(ctx, redis.Config{ ConnectionURL: "redis://localhost:6379/0", RetryAttempts: 3, RetryInterval: 5 * time.Second, ConnectTimeout: 30 * time.Second, }) if err != nil { panic(err) } defer client.Close() // Use the Redis client err = client.Set(ctx, "key", "value", time.Hour).Err() // ... } ``` -------------------------------- ### Generating Basic Random Names Go Source: https://github.com/dmitrymomot/gokit/blob/main/randomname/README.md Demonstrates importing the `randomname` package and using the `Generate` function to get a name with a unique suffix (e.g., "brave-tiger-1a2b3c"), and `GenerateSimple` to get a name without a suffix (e.g., "brave-tiger"). Both functions accept an optional validation callback. ```Go import "github.com/dmitrymomot/gokit/randomname" // Generate name with suffix (e.g., "brave-tiger-1a2b3c") name := randomname.Generate(nil) // Generate a simple name without suffix (e.g., "brave-tiger") simpleName := randomname.GenerateSimple(nil) ``` -------------------------------- ### Example Paginated JSON Response Source: https://github.com/dmitrymomot/gokit/blob/main/pagination/README.md This JSON snippet shows a typical structure for an API response that includes both the list of items and the pagination metadata generated by the package. ```json { "items": [ { "id": 1, "name": "Item 1" }, { "id": 2, "name": "Item 2" } ], "pagination": { "page": 2, "size": 10, "total_items": 58, "total_pages": 6 } } ``` -------------------------------- ### Load Mailer Config from Environment Go Source: https://github.com/dmitrymomot/gokit/blob/main/mailer/README.md Illustrates loading the mailer configuration from environment variables using the gokit config package before creating the mailer client. This approach promotes flexible deployment configurations. Requires the config and mailer packages. ```go import ( "github.com/dmitrymomot/gokit/config" "github.com/dmitrymomot/gokit/mailer" ) // Load configuration from environment variables cfg, err := config.Load[mailer.Config]() if err != nil { // Handle error } // Create client with loaded config client, err := mailer.NewClient(cfg) ``` -------------------------------- ### Defining Custom Go Sanitizer Function Source: https://github.com/dmitrymomot/gokit/blob/main/sanitizer/README.md Shows how to define a custom sanitizer function that conforms to the 'SanitizeFunc' signature required by the package. This example implements a simple profanity filter. ```Go func profanityFilterSanitizer(fieldValue any, fieldType reflect.StructField, params []string) any { if v, ok := fieldValue.(string); ok { profanity := []string{"bad", "words", "profanity"} result := v for _, word := range profanity { result = strings.ReplaceAll(result, word, "***") } return result } return fieldValue } ``` -------------------------------- ### Creating Pointers with utils.Ptr - Go Source: https://github.com/dmitrymomot/gokit/blob/main/utils/README.md Demonstrates the usage of the generic `utils.Ptr` function to create pointers to values of any type, eliminating the need for temporary variables. It shows initialization of a struct with pointer fields and application to various data types. Requires importing the `gokit/utils` package. ```Go import "github.com/dmitrymomot/gokit/utils" // Create pointers to values without separate variables type Config struct { Name string Enabled *bool Count *int Timeout *time.Duration } // Create a struct with pointer fields directly config := Config{ Name: "Example", Enabled: utils.Ptr(true), Count: utils.Ptr(42), Timeout: utils.Ptr(5 * time.Second), } // Works with any type stringPtr := utils.Ptr("hello") floatPtr := utils.Ptr(3.14) timePtr := utils.Ptr(time.Now()) customPtr := utils.Ptr(MyStruct{Field: "value"}) ```