### Blob Configuration Examples Source: https://github.com/justtrackio/gosoline/blob/main/pkg/blob/AGENTS.md Examples of configuring bucket naming patterns for blob stores. Supports global defaults, store-specific patterns, and explicit bucket names. ```yaml cloud.aws.s3.clients.default.naming.bucket_pattern: "{app.tags.project}-{app.env}-{app.name}-blobs-{bucketId}" ``` ```yaml cloud.aws.s3.clients.my_store_client.naming.bucket_pattern: "{app.env}-images-{app.tags.region}" ``` ```yaml blob.legacy.bucket: "my-legacy-bucket" ``` -------------------------------- ### SQS Input Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/pkg/stream/AGENTS.md Example configuration for an SQS input stream. Includes optional application name and tags, and the required queue ID. ```yaml stream: input: my-input: type: sqs application: target-app # optional, defaults to app.name tags: # optional project: my-project family: my-family group: my-group queue_id: my-queue ``` -------------------------------- ### Subscriber Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/pkg/mdlsub/AGENTS.md Example YAML configuration for setting up a subscriber, defining its input source and output target. This configuration specifies an SQS input and a DDB output. ```yaml subscribers: mymodel: input: type: sqs queue_id: model-changes output: type: ddb ``` -------------------------------- ### SNS Input with Targets Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/pkg/stream/AGENTS.md Example configuration for an SNS input stream that fans out to multiple targets. Demonstrates how to specify target applications, tags, and topic IDs. ```yaml stream: input: my-sns-input: type: sns id: my-consumer tags: # optional — identity of the SQS queue used for fan-out project: my-project family: my-family group: my-group targets: - application: target-app # optional — identity of the SNS topic to subscribe to tags: project: target-project family: target-family group: target-group topic_id: my-topic ``` -------------------------------- ### Publisher Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/pkg/mdlsub/AGENTS.md Example YAML configuration for setting up a publisher, specifying the output type and optional ModelId fields. Defaults for ModelId fields are derived from global application configuration. ```yaml mdlsub: publishers: mymodel: output_type: sns # or sqs / kinesis / kafka / in_memory # ModelId fields (all optional — defaults come from app config): # name: mymodel # defaults to the publisher map key # application: my-app # defaults to app.name # env: prod # defaults to app.env # tags: # project: my-project ``` -------------------------------- ### Run the HTTP Server Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/sampling-fingers-crossed/README.md Execute this command to start the Go HTTP server. The server will be accessible at http://127.0.0.1:8088. ```bash go run . ``` -------------------------------- ### Consumer Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/pkg/stream/AGENTS.md Example configuration for a stream consumer. Specifies the input type, encoding format, and retry settings. ```yaml stream: consumer: my-consumer: input: sqs encoding: json retry: enabled: true ``` -------------------------------- ### SQS Output Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/pkg/stream/AGENTS.md Example configuration for an SQS output stream. Shows optional fields like application name and tags, along with required queue ID and client name. ```yaml stream: output: my-output: type: sqs application: my-app # optional, defaults to app.name tags: # optional, merged with app.tags project: my-project family: my-family group: my-group queue_id: my-queue client_name: default ``` -------------------------------- ### CRUD Operations Example (Listing) Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Provides an example of listing entities using a POST request to a /v0/myEntities endpoint. Note that create, read, update, and delete operations are mentioned but not fully implemented in this specific test application. ```bash go run . ``` ```bash curl -XPOST http://127.0.0.1:8088/v0/myEntities -d '{}' ``` ```json {"total":2,"results":[{"id":1,"prop1":"text","prop2":"","createdAt":null,"updatedAt":null},{"id":2,"prop1":"text","prop2":"","createdAt":null,"updatedAt":null}]} ``` ```bash # create curl -XPOST http://127.0.0.1:8088/v0/myEntity -d '{"prop1:"test"}' # read curl http://127.0.0.1:8088/v0/myEntity/1 # update curl -XPUT http://127.0.0.1:8088/v0/myEntity/1 -d '{"prop1:"test"}' # delete curl -XDELETE http://127.0.0.1:8088/v0/myEntity/1 ``` -------------------------------- ### Define gRPC Services and Registrant Source: https://github.com/justtrackio/gosoline/blob/main/examples/grpcserver/README.md Implement the `Definer` function to create and register gRPC services. This example shows how to define a Greeter service and its registrant function. ```go func Definer(_ context.Context, config cfg.Config, logger log.Logger) (*grpcserver.Definitions, error) { defs := &grpcserver.Definitions{} greeter := NewGreeterService(config, logger) defs.Add(GreeterServiceName, greeterRegistrant(greeter)) return defs, nil } func greeterRegistrant(greeterServer protobuf.GreeterServer) grpcserver.Registrant { return func(server *grpc.Server) error { protobuf.RegisterGreeterServer(server, greeterServer) return nil } } ``` -------------------------------- ### Load Redis Fixtures with NewSimpleFixtureSet Source: https://context7.com/justtrackio/gosoline/llms.txt Demonstrates how to create a FixtureSet for Redis using `NewSimpleFixtureSet`. This involves defining named fixtures with Redis-specific values and expiry times, and providing a `redis.RedisFixtureWriter`. This setup is typically registered via `application.WithFixtureSetFactory`. ```go //go:build fixtures package main import ( "context" "time" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/fixtures" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" "github.com/justtrackio/gosoline/pkg/redis" ) func redisSessionFixtures(ctx context.Context, config cfg.Config, logger log.Logger) (fixtures.FixtureSet, error) { writer, err := redis.NewRedisFixtureWriter(ctx, config, logger, "default", redis.RedisOpSet) if err != nil { return nil, err } return fixtures.NewSimpleFixtureSet(fixtures.NamedFixtures[*redis.RedisFixture]{ { Name: "session-alice", Value: &redis.RedisFixture{ Key: "session:user:alice", Value: `{"user_id":"alice","role":"admin"}`, Expiry: 24 * time.Hour, }, }, { Name: "session-bob", Value: &redis.RedisFixture{ Key: "session:user:bob", Value: `{"user_id":"bob","role":"viewer"}`, Expiry: 24 * time.Hour, }, }, }, writer), nil } func fixtureFactory(ctx context.Context, config cfg.Config, logger log.Logger, group string) ([]fixtures.FixtureSet, error) { redisFs, err := redisSessionFixtures(ctx, config, logger) if err != nil { return nil, err } return []fixtures.FixtureSet{redisFs}, nil } func main() { application.Run( application.WithConfigFile("config.dist.yml", "yml"), application.WithFixtureSetFactory("default", fixtureFactory), application.WithModuleFactory("main", func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { return &struct{ kernel.ForegroundModule }{}, nil }), ) } // Run with: go run -tags fixtures . ``` -------------------------------- ### Common DB Configuration Keys Source: https://github.com/justtrackio/gosoline/blob/main/pkg/db/AGENTS.md Example configuration for a default MySQL database connection, including settings for driver, hostname, port, database name, username, password, and migrations. ```yaml db.default.driver: mysql db.default.hostname: localhost db.default.port: 3306 db.default.database: mydb db.default.username: root db.default.password: "" db.default.migrations.enabled: true db.default.migrations.path: migrations ``` -------------------------------- ### Base Test Suite Pattern Source: https://github.com/justtrackio/gosoline/blob/main/pkg/test/AGENTS.md Define custom test suites by embedding 'suite.Suite' and implementing SetupSuite/TearDownSuite for environment setup and cleanup. Use 'suite.Run' to execute the tests. ```go import "github.com/justtrackio/gosoline/pkg/test/suite" type MySuite struct { suite.Suite } func (s *MySuite) SetupSuite() { // Start containers, load fixtures } func (s *MySuite) TearDownSuite() { // Stop containers } func TestMySuite(t *testing.T) { suite.Run(t, new(MySuite)) } ``` -------------------------------- ### Configure Redis Key Pattern Source: https://github.com/justtrackio/gosoline/blob/main/pkg/kvstore/AGENTS.md Examples of configuring Redis key patterns globally or per store. These patterns use placeholders for dynamic key generation. ```yaml kvstore.default.redis.key_pattern: "{app.tags.project}:{app.env}:{store}:{key}" ``` ```yaml kvstore.cache.redis.key_pattern: "cache:{key}" ``` ```yaml kvstore.default.redis.key_pattern: "{app.namespace}-kvstore-{store}-{key}" ``` -------------------------------- ### Prometheus Metrics Output Example Source: https://github.com/justtrackio/gosoline/blob/main/examples/metrics/prometheus/README.md Sample output of custom metrics exposed via the /metrics endpoint. This shows counter and gauge metrics with labels. ```text # HELP gosoline:dev:metrics:prometheus_ApiRequestCount unit: Count # TYPE gosoline:dev:metrics:prometheus_ApiRequestCount counter gosoline:dev:metrics:prometheus_ApiRequestCount{path="/current-value"} 4 gosoline:dev:metrics:prometheus_ApiRequestCount{path="/decrease"} 4 gosoline:dev:metrics:prometheus_ApiRequestCount{path="/increase"} 5 # HELP gosoline:dev:metrics:prometheus_ApiRequestResponseTime unit: UnitMillisecondsAverage # TYPE gosoline:dev:metrics:prometheus_ApiRequestResponseTime gauge gosoline:dev:metrics:prometheus_ApiRequestResponseTime{path="/current-value"} 0.042044 gosoline:dev:metrics:prometheus_ApiRequestResponseTime{path="/decrease"} 0.040718 gosoline:dev:metrics:prometheus_ApiRequestResponseTime{path="/increase"} 0.044629 # HELP gosoline:dev:metrics:prometheus_ApiStatus2XX unit: Count # TYPE gosoline:dev:metrics:prometheus_ApiStatus2XX counter gosoline:dev:metrics:prometheus_ApiStatus2XX{path="/current-value"} 4 gosoline:dev:metrics:prometheus_ApiStatus2XX{path="/decrease"} 4 gosoline:dev:metrics:prometheus_ApiStatus2XX{path="/increase"} 5 # HELP gosoline:dev:metrics:prometheus_api_request unit: prom-counter # TYPE gosoline:dev:metrics:prometheus_api_request counter gosoline:dev:metrics:prometheus_api_request{handler="cur"} 4 gosoline:dev:metrics:prometheus_api_request{handler="decr"} 4 gosoline:dev:metrics:prometheus_api_request{handler="incr"} 5 # HELP gosoline:dev:metrics:prometheus_important_counter unit: Count # TYPE gosoline:dev:metrics:prometheus_important_counter counter gosoline:dev:metrics:prometheus_important_counter 25 ``` -------------------------------- ### gRPC Server Configuration Example Source: https://github.com/justtrackio/gosoline/blob/main/examples/grpcserver/README.md Configure the gRPC server's port and health check settings by adding this snippet to your configuration file or setting environment variables. ```yaml grpc_server: default: port: 8080 health: enabled: true ``` -------------------------------- ### Define Module Interface Source: https://github.com/justtrackio/gosoline/blob/main/pkg/kernel/AGENTS.md Implement this interface for modules that will be managed by the kernel. The Run method is called when the module is started. ```go type Module interface { Run(ctx context.Context) error } ``` ```go type ModuleFactory func(ctx context.Context, config cfg.Config, logger log.Logger) (Module, error) ``` -------------------------------- ### Get Identity from Configuration Source: https://github.com/justtrackio/gosoline/blob/main/pkg/cfg/AGENTS.md Retrieves the identity object from the configuration. This is the primary method for accessing identity information. ```go identity, err := cfg.GetIdentity(config) ``` -------------------------------- ### Configure macOS for Integration Tests Source: https://github.com/justtrackio/gosoline/blob/main/README.md On macOS, you need to alias the loopback interface with a specific IP address before running integration tests. This is a one-time setup or required after system updates. ```shell sudo ifconfig lo0 alias 172.17.0.1 ``` -------------------------------- ### Redis Key Naming Pattern - Custom Tags Source: https://github.com/justtrackio/gosoline/blob/main/pkg/redis/AGENTS.md An example of a Redis key naming pattern that includes custom tags like region and team. ```yaml redis.default.naming.key_pattern: "{app.tags.region}-{app.tags.team}-{app.env}-{key}" ``` -------------------------------- ### POST Request with Form Input Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Illustrates making POST requests with form data to an endpoint. Shows examples of incorrect usage leading to errors and a successful call with valid JSON input. ```bash go run . ``` ```bash curl -XPOST http://127.0.0.1:8088/json-handler ``` ```json {"err":"EOF"} ``` ```bash curl -XPOST http://127.0.0.1:8088/json-handler -d '{}' ``` ```json {"err":"Key: 'inputEntity.Message' Error:Field validation for 'Message' failed on the 'required' tag"} ``` ```bash curl -XPOST http://127.0.0.1:8088/json-handler -d '{"message":"hello, please handle this"}' ``` ```json {"message":"Thank you for submitting your message 'hello, please handle this', we will handle it with care!"} ``` -------------------------------- ### Bootstrap and Run Gosoline Application Source: https://context7.com/justtrackio/gosoline/llms.txt Use `application.Run` as the entry point for your Gosoline service. Configure it with options to load config files, set specific settings, enable subsystems like metrics and tracing, and register foreground or background modules. ```go package main import ( "context" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" ) func main() { application.Run( // Load YAML config application.WithConfigFile("config.dist.yml", "yml"), // Override a single setting programmatically application.WithConfigSetting("my_service.timeout", "30s"), // Enable CloudWatch + Prometheus metrics application.WithMetrics, // Enable distributed tracing application.WithTracing, // Register a background module application.WithModuleFactory("worker", NewWorkerModule, kernel.ModuleType(kernel.TypeBackground)), // Register a foreground module (application exits when it stops) application.WithModuleFactory("job", NewJobModule, kernel.ModuleType(kernel.TypeForeground)), ) } func NewWorkerModule(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { return &WorkerModule{logger: logger.WithChannel("worker")}, nil } type WorkerModule struct{ logger log.Logger } func (w *WorkerModule) Run(ctx context.Context) error { w.logger.Info(ctx, "worker started") <-ctx.Done() w.logger.Info(ctx, "worker stopping") return nil } func NewJobModule(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { return &JobModule{logger: logger.WithChannel("job")}, nil } type JobModule struct{ logger log.Logger } func (j *JobModule) Run(ctx context.Context) error { j.logger.Info(ctx, "job executed once, exiting") return nil // returning nil causes foreground module to stop, kernel shuts down } ``` -------------------------------- ### GET Request Returning JSON Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Demonstrates how to make GET requests to endpoints that return JSON data, either from a map or a struct. ```APIDOC ## GET /json-from-map ### Description Retrieves a JSON response from a map. ### Method GET ### Endpoint `/json-from-map` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request, typically "success". ### Response Example ```json { "status": "success" } ``` ## GET /json-from-struct ### Description Retrieves a JSON response from a struct. ### Method GET ### Endpoint `/json-from-struct` ### Response #### Success Response (200) - **status** (string) - Indicates the status of the request, typically "success". ### Response Example ```json { "status": "success" } ``` ``` -------------------------------- ### Get Canonical Model ID String Representation Source: https://github.com/justtrackio/gosoline/blob/main/pkg/mdl/AGENTS.md Use this to get the canonical string representation of a ModelId, defined by app.model_id.domain_pattern. Ensure the ModelId is padded from configuration first. ```go modelId := mdl.ModelId{Name: "users"} modelId.PadFromConfig(config) canonical := modelId.String() // Result: "myproject.production.myfamily.mygroup.users" ``` -------------------------------- ### Run Gosoline Application with Module Factory Source: https://github.com/justtrackio/gosoline/blob/main/README.md This Go code demonstrates the basic structure of a Gosoline application. It shows how to use `application.Run` with a custom module factory. Ensure the `NewHelloWorldModule` function and `HelloWorldModule` struct are defined to handle application logic. ```go package main import ( "context" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" ) func main() { application.Run( application.WithModuleFactory("hello-world", NewHelloWorldModule), ) } func NewHelloWorldModule(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { return &HelloWorldModule{ logger: logger.WithChannel("hello-world"), }, nil } type HelloWorldModule struct { logger log.Logger } func (h HelloWorldModule) Run(ctx context.Context) error { h.logger.Info(ctx, "Hello World") return nil } ``` -------------------------------- ### GET Request Returning JSON Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Demonstrates how to make GET requests to endpoints that return JSON data, either from a map or a struct. Ensure the server is running before executing curl commands. ```bash go run . ``` ```bash curl http://127.0.0.1:8088/json-from-map curl http://127.0.0.1:8088/json-from-struct ``` ```json {"status":"success"} ``` -------------------------------- ### Run Default HTTP Server with Custom Routes Source: https://context7.com/justtrackio/gosoline/llms.txt Launches a default HTTP server using a provided definer function to wire routes. Ensure the configuration specifies the server port. ```go package main import ( "context" "net/http" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/httpserver" "github.com/justtrackio/gosoline/pkg/log" ) type CreateUserInput struct { Name string `json:"name" binding:"required"` Email string `json:"email" binding:"required,email" } type CreateUserHandler struct{} func (h *CreateUserHandler) GetInput() any { return &CreateUserInput{} } func (h *CreateUserHandler) Handle(ctx context.Context, req *httpserver.Request) (*httpserver.Response, error) { input := req.Body.(*CreateUserInput) // ... persist user ... return httpserver.NewJsonResponse(map[string]string{ "status": "created", "name": input.Name, }), nil } type StatusHandler struct{} func (h *StatusHandler) Handle(ctx context.Context, req *httpserver.Request) (*httpserver.Response, error) { return httpserver.NewJsonResponse(map[string]string{"status": "ok"}), nil } func defineRoutes(ctx context.Context, config cfg.Config, logger log.Logger) (*httpserver.Definitions, error) { d := &httpserver.Definitions{} // GET /status -> no input binding d.GET("/status", httpserver.CreateHandler(&StatusHandler{})) // POST /users -> JSON body binding d.POST("/users", httpserver.CreateJsonHandler(&CreateUserHandler{})) // Grouped routes under /v1 v1 := d.Group("/v1") v1.GET("/health", httpserver.CreateHandler(&StatusHandler{})) return d, nil } func main() { // config.dist.yml must set httpserver.default.port (default 8080) application.RunHttpDefaultServer(defineRoutes, application.WithConfigFile("config.dist.yml", "yml"), ) } // curl http://localhost:8080/status // {"status":"ok"} // // curl -X POST http://localhost:8080/users -H 'Content-Type: application/json' \ // -d '{"name":"Alice","email":"alice@example.com"}' // {"name":"Alice","status":"created"} ``` -------------------------------- ### application.RunHttpDefaultServer Source: https://context7.com/justtrackio/gosoline/llms.txt Launches a default HTTP API server. It internally initializes an HTTP server, registers modules, and wires routes using a provided Definer function. ```APIDOC ## application.RunHttpDefaultServer — Launch an HTTP API server Convenience runner for a single named `"default"` HTTP server. Internally calls `httpserver.New("default", definer)` and registers the module. The `Definer` function wires routes onto a `*Definitions` object. ### Usage ```go application.RunHttpDefaultServer(defineRoutes, application.WithConfigFile("config.dist.yml", "yml"), ) ``` ### Parameters - `definer` (func(context.Context, cfg.Config, log.Logger) (*httpserver.Definitions, error)): A function that defines the routes for the HTTP server. - `options` ([]application.Option): Optional configuration options for the application runner. ``` -------------------------------- ### CRUD Operations (Conceptual) Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Provides examples for conceptual CRUD operations on entities, though full implementation details are not shown. ```APIDOC ## POST /v0/myEntities ### Description Lists existing entities. This example primarily demonstrates listing. ### Method POST ### Endpoint `/v0/myEntities` ### Response #### Success Response (200) - **total** (integer) - The total number of entities. - **results** (array) - An array of entity objects. - **id** (integer) - The unique identifier of the entity. - **prop1** (string) - A property of the entity. - **prop2** (string) - Another property of the entity. - **createdAt** (string) - The timestamp when the entity was created. - **updatedAt** (string) - The timestamp when the entity was last updated. ### Response Example ```json { "total": 2, "results": [ { "id": 1, "prop1": "text", "prop2": "", "createdAt": null, "updatedAt": null }, { "id": 2, "prop1": "text", "prop2": "", "createdAt": null, "updatedAt": null } ] } ``` ## POST /v0/myEntity ### Description Creates a new entity. (Note: Implementation details for creation are not fully provided in the source). ### Method POST ### Endpoint `/v0/myEntity` ### Parameters #### Request Body - **prop1** (string) - Required - The first property of the entity. ### Request Example ```json { "prop1":"test" } ``` ## GET /v0/myEntity/{id} ### Description Retrieves a specific entity by its ID. ### Method GET ### Endpoint `/v0/myEntity/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the entity to retrieve. ## PUT /v0/myEntity/{id} ### Description Updates an existing entity by its ID. ### Method PUT ### Endpoint `/v0/myEntity/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the entity to update. #### Request Body - **prop1** (string) - Required - The updated value for the first property. ### Request Example ```json { "prop1":"test" } ``` ## DELETE /v0/myEntity/{id} ### Description Deletes a specific entity by its ID. ### Method DELETE ### Endpoint `/v0/myEntity/{id}` ### Parameters #### Path Parameters - **id** (integer) - Required - The ID of the entity to delete. ``` -------------------------------- ### API Key and HTTP Basic Authentication Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Demonstrates how to secure an endpoint using both API key and HTTP Basic authentication. Shows requests with missing credentials, incorrect credentials, and successful authentication using both methods. ```bash go run . ``` ```bash curl http://127.0.0.1:8088/admin/authenticated ``` ```json {"api-key":"no api key provided","basic-auth":"no credentials provided"} ``` ```bash curl -H 'X-API-KEY: someKey' http://127.0.0.1:8088/admin/authenticated ``` ```json {"api-key":"api key does not match","basic-auth":"no credentials provided"} ``` ```bash curl -H 'X-API-KEY: changeMe' http://127.0.0.1:8088/admin/authenticated ``` ```json {"authenticated":true} ``` ```bash curl -H 'Authorization: Basic YWRtaW46cGFzc3dvcmQ=' http://127.0.0.1:8088/admin/authenticated ``` ```json {"authenticated":true} ``` -------------------------------- ### Publish Model Events with mdlsub.NewPublisher Source: https://context7.com/justtrackio/gosoline/llms.txt Demonstrates how to create a publisher for model events and publish individual or batched events. Ensure the configuration defines the producer for the publisher. ```go package main import ( "context" "fmt" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" "github.com/justtrackio/gosoline/pkg/mdlsub" ) type ProductModel struct { ID uint `json:"id"` Name string `json:"name"` Price float64 `json:"price"` } type ProductService struct { publisher mdlsub.Publisher logger log.Logger } func NewProductService(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { // config must define mdlsub.publishers.product.producer = "product-events" pub, err := mdlsub.NewPublisher(ctx, config, logger, "product") if err != nil { return nil, fmt.Errorf("can not create product publisher: %w", err) } return &ProductService{publisher: pub, logger: logger.WithChannel("product-service")}, nil } func (s *ProductService) Run(ctx context.Context) error { product := &ProductModel{ID: 1, Name: "Gosoline T-Shirt", Price: 29.99} // Publish a "create" event at version 1 if err := s.publisher.Publish(ctx, mdlsub.TypeCreate, 1, product); err != nil { return fmt.Errorf("failed to publish create event: %w", err) } s.logger.Info(ctx, "published create event for product %d", product.ID) product.Price = 24.99 // Publish an "update" event if err := s.publisher.Publish(ctx, mdlsub.TypeUpdate, 1, product); err != nil { return fmt.Errorf("failed to publish update event: %w", err) } s.logger.Info(ctx, "published update event for product %d", product.ID) // Publish a batch batch := []any{ &ProductModel{ID: 2, Name: "Hoodie", Price: 49.99}, &ProductModel{ID: 3, Name: "Cap", Price: 19.99}, } if err := s.publisher.PublishBatch(ctx, mdlsub.TypeCreate, 1, batch); err != nil { return fmt.Errorf("failed to publish batch: %w", err) } return nil } func main() { application.Run( application.WithConfigFile("config.dist.yml", "yml"), application.WithProducerDaemon, application.WithModuleFactory("product-service", NewProductService), ) } ``` -------------------------------- ### Required Configuration Keys for Application Source: https://github.com/justtrackio/gosoline/blob/main/pkg/application/AGENTS.md Defines essential configuration keys for application environment, name, and tags. Ensure these are present for proper application startup and resource naming. ```yaml app: env: dev # Environment name (required) name: myapp # Application name (required) tags: project: myproject # Project identifier family: myfamily # Family grouping group: mygroup # Group within family ``` -------------------------------- ### Test Normal HTTP Request Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/sampling-fingers-crossed/README.md Use this cURL command to send a standard GET request to the /success endpoint. This helps verify basic server functionality. ```bash curl -i http://127.0.0.1:8088/success ``` -------------------------------- ### Enable Fixtures Build Tag Source: https://github.com/justtrackio/gosoline/blob/main/pkg/fixtures/AGENTS.md All fixture code requires the `fixtures` build tag. Compile and test with `go test -tags fixtures ./...`. ```go //go:build fixtures package fixtures ``` -------------------------------- ### Generate gRPC Services with Protoc Source: https://github.com/justtrackio/gosoline/blob/main/examples/grpcserver/README.md Use the `protoc` command to generate Go code for gRPC services from your `.proto` definition files. Specify output paths and plugins for gRPC. ```shell protoc --go_opt=paths=source_relative --go_out=plugins=grpc:. helloworld.proto ``` -------------------------------- ### Execute Integration Tests on Linux Source: https://github.com/justtrackio/gosoline/blob/main/README.md Run integration tests with fixtures enabled on Linux systems. Ensure you are in the correct project directory. ```shell go test -tags integration,fixtures ./test/... ``` -------------------------------- ### Redis Key Pattern Processing Logic Source: https://github.com/justtrackio/gosoline/blob/main/pkg/redis/AGENTS.md Illustrates how the Redis key pattern is processed in `client.go` to derive a prefix for all Redis keys. ```go // The prefix is derived from the key pattern by removing the {key} suffix. // For example, pattern "{app.namespace}-{app.name}-{key}" produces prefix "{app.namespace}-{app.name}-". // All Redis operations then prepend this expanded prefix to the application key. ``` -------------------------------- ### Create Scoped Loggers with Fields in Go Source: https://context7.com/justtrackio/gosoline/llms.txt Shows how to create a logger instance with a specific channel and additional fields for structured logging. Error logging automatically wraps the provided error. ```go package main import ( "context" "fmt" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" ) func NewOrderProcessor(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { // Create a channel-scoped logger (appears in log output as channel=order-processor) procLogger := logger.WithChannel("order-processor") return &OrderProcessor{ logger: procLogger.WithFields(log.Fields{ "component": "processor", "version": "1.0", }), }, nil } type OrderProcessor struct{ logger log.Logger } func (p *OrderProcessor) Run(ctx context.Context) error { orderID := "ord-42" p.logger.Debug(ctx, "starting to process order %s", orderID) p.logger.Info(ctx, "processing order %s with %d items", orderID, 3) if err := processOrder(orderID); err != nil { // Error auto-wraps the format into an error and logs the full chain p.logger.Error(ctx, "failed to process order %s: %w", orderID, err) return err } p.logger.Info(ctx, "order %s processed successfully", orderID) return nil } func processOrder(id string) error { if id == "" { return fmt.Errorf("empty order id") } return nil } // config.dist.yml: // log: // handlers: // main: // type: iowriter // level: info // formatter: console // writer: stdout // // Output: // 15:04:05.123 order-processor info processing order ord-42 with 3 items component: processor version: 1.0 ``` -------------------------------- ### Implement Distributed Tracing with tracing.ProvideTracer Source: https://context7.com/justtrackio/gosoline/llms.txt Use tracing.ProvideTracer to obtain a Tracer for AWS X-Ray or OpenTelemetry. Spans can be created using StartSpanFromContext for root spans or StartSubSpan for child spans, propagating trace context via context.Context. Ensure the application is configured with application.WithTracing. ```go package main import ( "context" "fmt" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" "github.com/justtrackio/gosoline/pkg/tracing" ) type TracedService struct { tracer tracing.Tracer logger log.Logger } func NewTracedService(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { tracer, err := tracing.ProvideTracer(ctx, config, logger) if err != nil { return nil, fmt.Errorf("can not create tracer: %w", err) } return &TracedService{tracer: tracer, logger: logger.WithChannel("traced-service")}, nil } func (s *TracedService) Run(ctx context.Context) error { // Start a root span ctx, span := s.tracer.StartSpanFromContext(ctx, "process-batch") defer span.Finish() if err := s.processItem(ctx, "item-1"); err != nil { span.AddError(err) return err } return nil } func (s *TracedService) processItem(ctx context.Context, id string) error { // Create a child (sub) span ctx, subSpan := s.tracer.StartSubSpan(ctx, "process-item") defer subSpan.Finish() s.logger.Info(ctx, "processing item %s", id) // trace ID is auto-injected into log fields return nil } func main() { // config.dist.yml: // tracing: // provider: otel # or "aws" for X-Ray application.Run( application.WithConfigFile("config.dist.yml", "yml"), application.WithTracing, application.WithModuleFactory("traced-service", NewTracedService), ) } ``` -------------------------------- ### Pad Identity from Configuration Source: https://github.com/justtrackio/gosoline/blob/main/pkg/cfg/AGENTS.md Fills empty fields of an existing Identity object using values from the configuration. Useful for partially populated Identity objects. ```go // Fill empty fields of Identity from config // Useful when you have a partially populated Identity err := identity.PadFromConfig(config) ``` -------------------------------- ### Configure Fixtures Source: https://github.com/justtrackio/gosoline/blob/main/pkg/fixtures/AGENTS.md Enable fixtures globally and specify active groups using configuration keys. ```yaml fixtures.enabled: true fixtures.groups: - default - integration ``` -------------------------------- ### API Key and HTTP Basic Authentication Source: https://github.com/justtrackio/gosoline/blob/main/examples/httpserver/simple-handlers/README.md Demonstrates how to secure an endpoint using both API Key and HTTP Basic Authentication. ```APIDOC ## GET /admin/authenticated ### Description An endpoint protected by API Key and HTTP Basic Authentication. ### Method GET ### Endpoint `/admin/authenticated` ### Parameters #### Request Headers - **X-API-KEY** (string) - Required - The API key for authentication. - **Authorization** (string) - Required - The Basic Authentication token. ### Response #### Success Response (200) - **authenticated** (boolean) - Indicates if the authentication was successful. ### Response Example ```json { "authenticated": true } ``` ``` -------------------------------- ### Gosoline Application Configuration Source: https://github.com/justtrackio/gosoline/blob/main/README.md This YAML file defines the default configuration for a Gosoline application. It sets environment, project, family, and name parameters. ```yaml env: dev app_project: gosoline app_family: example app_name: application ``` -------------------------------- ### Common Matchers for Mocking Source: https://github.com/justtrackio/gosoline/blob/main/pkg/test/AGENTS.md Use these matchers with mocking libraries like gomock to assert specific values in function calls. Import the 'matcher' package to access them. ```go import "github.com/justtrackio/gosoline/pkg/test/matcher" // Match any context mock.EXPECT().Method(matcher.Context).Return(nil) // Match specific time mock.EXPECT().Method(matcher.Time(expectedTime)).Return(nil) ``` -------------------------------- ### Add gRPC Server Module to Kernel Source: https://github.com/justtrackio/gosoline/blob/main/examples/grpcserver/README.md Integrate the gRPC Server module into your gosoline application kernel by adding it using `app.Add()`. Ensure you provide a `Definer` for service registration. ```go app := application.New() app.Add("grpc_server", grpcserver.New(service.Definer)) ``` -------------------------------- ### Create DynamoDB Repository and Perform CRUD Operations Source: https://context7.com/justtrackio/gosoline/llms.txt This snippet demonstrates how to create a typed DynamoDB repository using `ddb.NewRepository` and perform common CRUD operations such as PutItem, GetItem, and Query. Ensure your struct tags are correctly defined for DynamoDB keys and that the model name matches your table. ```go package main import ( "context" "fmt" "github.com/justtrackio/gosoline/pkg/application" "github.com/justtrackio/gosoline/pkg/cfg" "github.com/justtrackio/gosoline/pkg/ddb" "github.com/justtrackio/gosoline/pkg/kernel" "github.com/justtrackio/gosoline/pkg/log" "github.com/justtrackio/gosoline/pkg/mdl" ) type UserItem struct { UserID string `ddb:"key=hash" CreatedAt string `ddb:"key=range" Name string Email string } type UserService struct { repo ddb.Repository logger log.Logger } func NewUserService(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) { repo, err := ddb.NewRepository(ctx, config, logger, &ddb.Settings{ ModelId: mdl.ModelId{Name: "users"}, Main: ddb.MainSettings{ Model: UserItem{}, ReadCapacityUnits: 5, WriteCapacityUnits: 5, }, }) if err != nil { return nil, fmt.Errorf("can not create user repository: %w", err) } return &UserService{repo: repo, logger: logger.WithChannel("user-service")}, nil } func (s *UserService) Run(ctx context.Context) error { // Put an item user := &UserItem{UserID: "u-1", CreatedAt: "2024-01-01T00:00:00Z", Name: "Alice", Email: "alice@example.com"} if _, err := s.repo.PutItem(ctx, nil, user); err != nil { return fmt.Errorf("failed to put user: %w", err) } // Get an item by key found := &UserItem{UserID: "u-1", CreatedAt: "2024-01-01T00:00:00Z"} result, err := s.repo.GetItem(ctx, nil, found) if err != nil { return fmt.Errorf("failed to get user: %w", err) } if result.IsFound { s.logger.Info(ctx, "found user: %s <%s>", found.Name, found.Email) } // Query by hash key var users []UserItem qb := s.repo.QueryBuilder().WithHash("u-1") if _, err := s.repo.Query(ctx, qb, &users); err != nil { return fmt.Errorf("failed to query users: %w", err) } s.logger.Info(ctx, "found %d users", len(users)) return nil } func main() { application.Run( application.WithConfigFile("config.dist.yml", "yml"), application.WithModuleFactory("user-service", NewUserService), ) } ``` -------------------------------- ### Generate gRPC Services with Go Generate Source: https://github.com/justtrackio/gosoline/blob/main/examples/grpcserver/README.md Embed the `protoc` command within a `//go:generate` directive in a `gen.go` file to easily regenerate gRPC services and serialization methods using `go generate`. ```go //go:build ignore package protobuf //go:generate protoc --go_opt=paths=source_relative --go_out=plugins=grpc:. helloworld.proto ``` -------------------------------- ### Format Identity with Resource Placeholders Source: https://github.com/justtrackio/gosoline/blob/main/pkg/cfg/AGENTS.md Formats a naming pattern using identity information and resource-specific placeholders. Supports validation of unknown placeholders and tag requirements based on pattern usage. ```go // Format a pattern with resource placeholder name, err := identity.Format(pattern, delimiter, map[string]string{ "queueId": "my-queue", }) ```