{"id":13413398,"url":"https://github.com/mehdihadeli/Go-MediatR","last_synced_at":"2025-03-14T19:32:09.756Z","repository":{"id":45008870,"uuid":"513063741","full_name":"mehdihadeli/Go-MediatR","owner":"mehdihadeli","description":"🚃 A library for handling mediator patterns and simplified CQRS patterns within an event-driven architecture, inspired by csharp MediatR library.","archived":false,"fork":false,"pushed_at":"2024-09-16T22:42:04.000Z","size":180,"stargazers_count":204,"open_issues_count":3,"forks_count":16,"subscribers_count":8,"default_branch":"main","last_synced_at":"2024-09-17T03:30:43.419Z","etag":null,"topics":["cqrs","go","golang","golang-package","mediator","mediator-pattern"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/mehdihadeli/go-mediatr","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mehdihadeli.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2022-07-12T08:40:01.000Z","updated_at":"2024-09-16T22:43:00.000Z","dependencies_parsed_at":"2024-01-15T15:47:43.487Z","dependency_job_id":"5b0223dd-d240-4f28-8d29-b8c7e2d8fa17","html_url":"https://github.com/mehdihadeli/Go-MediatR","commit_stats":null,"previous_names":["mehdihadeli/mediatr"],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehdihadeli%2FGo-MediatR","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehdihadeli%2FGo-MediatR/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehdihadeli%2FGo-MediatR/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mehdihadeli%2FGo-MediatR/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mehdihadeli","download_url":"https://codeload.github.com/mehdihadeli/Go-MediatR/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":221498743,"owners_count":16833055,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cqrs","go","golang","golang-package","mediator","mediator-pattern"],"created_at":"2024-07-30T20:01:39.407Z","updated_at":"2024-10-26T05:30:50.479Z","avatar_url":"https://github.com/mehdihadeli.png","language":"Go","funding_links":[],"categories":["Messaging","消息","Go"],"sub_categories":["Search and Analytic Databases","检索及分析资料库"],"readme":"\u003cdiv align=\"center\" style=\"margin-bottom:20px\"\u003e\n  \u003cimg src=\"assets/Go-MediatR.png\" alt=\"go-mediatr\" /\u003e\n  \u003cdiv align=\"center\"\u003e\n    \u003ca href=\"https://github.com/mehdihadeli/Go-MediatR/actions/workflows/ci.yml\"\u003e\u003cimg alt=\"build-status\" src=\"https://github.com/mehdihadeli/Go-MediatR/actions/workflows/ci.yml/badge.svg?branch=main\u0026style=flat-square\"/\u003e\u003c/a\u003e\n    \u003ca href=\"https://goreportcard.com/report/github.com/mehdihadeli/Go-MediatR\" \u003e\u003cimg alt=\"go report\" src=\"https://goreportcard.com/badge/github.com/mehdihadeli/Go-MediatR\"/\u003e\u003c/a\u003e\n    \u003ca\u003e\u003cimg alt=\"license\" src=\"https://img.shields.io/badge/go%20version-%3E=1.18-61CFDD.svg?style=flat-square\"/\u003e\u003c/a\u003e\n    \u003ca href=\"https://github.com/mehdihadeli/Go-MediatR/blob/main/LICENCE\"\u003e\u003cimg alt=\"build-status\" src=\"https://img.shields.io/github/license/mehdihadeli/Go-MediatR?color=%234275f5\u0026style=flat-square\"/\u003e\u003c/a\u003e\n    \u003ca href=\"https://coveralls.io/github/mehdihadeli/Go-MediatR?branch=main\"\u003e\u003cimg alt=\"Coverage Status\" src=\"https://img.shields.io/coveralls/github/mehdihadeli/Go-MediatR?color=%23f542cb\u0026style=flat-square\"/\u003e\u003c/a\u003e\n    \u003ca href=\"https://pkg.go.dev/github.com/mehdihadeli/go-mediatr\"\u003e\u003cimg alt=\"build-status\" src=\"https://pkg.go.dev/badge/github.com/mehdihadeli/go-mediatr\"/\u003e\u003c/a\u003e\n  \u003c/div\u003e\n\u003c/div\u003e\n\n\u003e This package is a `Mediator Pattern` implementation in golang, and inspired by great [jbogard/mediatr](https://github.com/jbogard/mediatr) library in .Net.\n\nFor decoupling some objects in a system we could use `Mediator` object as an interface, for decrease coupling between the objects. Mostly I uses this pattern when I use CQRS in my system.\n\nThere are some samples for using this package [here](internal/examples), also I used this packages widely in [this microservices sample](https://github.com/mehdihadeli/store-golang-microservices)\n\n## 🧰 Installation\n\n```bash\ngo get github.com/mehdihadeli/go-mediatr\n```\n\n## 🔥 Features\n✅ Handling `Request/Response` message for delivering message to only one handler (Commands, Queries)\n\n✅ Handling `Notification` message for delivering message to multiple handlers (Events)\n\n✅ `Pipelenes Behaviours` for handling some cross cutting concerns before or after executing handlers \n\n## 🛡️ Strategies\nMediatr has two strategies for dispatching messages:\n\n1. `Request/Response` messages, dispatched to a `single handler`.\n2. `Notification` messages, dispatched to all (multiple) `handlers` and they don't have any response.\n\n### Request/Response Strategy\nThe `request/response` message, has just `one handler`, and can handle both command and query scenarios in [CQRS Pattern](https://martinfowler.com/bliki/CQRS.html).\n\n#### Creating a Request/Response Message\n\nFor creating a request (command or query) that has just `one handler`, we could create a command message or query message as a `request` like this:\n\n```go\n// Command (Request)\ntype CreateProductCommand struct {\n    ProductID   uuid.UUID `validate:\"required\"`\n    Name        string    `validate:\"required,gte=0,lte=255\"`\n    Description string    `validate:\"required,gte=0,lte=5000\"`\n    Price       float64   `validate:\"required,gte=0\"`\n    CreatedAt   time.Time `validate:\"required\"`\n}\n\n// Query (Request)\ntype GetProdctByIdQuery struct {\n    ProductID uuid.UUID `validate:\"required\"`\n}\n```\nAnd for response of these requests, we could create response messages as a `response` like this:\n\n```go\n// Command (Response)\ntype CreateProductCommandResponse struct {\n    ProductID uuid.UUID `json:\"productId\"`\n}\n\n// Query (Response)\ntype GetProductByIdQueryResponse struct {\n    ProductID   uuid.UUID `json:\"productId\"`\n    Name        string    `json:\"name\"`\n    Description string    `json:\"description\"`\n    Price       float64   `json:\"price\"`\n    CreatedAt   time.Time `json:\"createdAt\"`\n}\n```\n\n#### Creating Request Handler\n\nFor handling our requests, we should create a `single request handler` for each request. Each handler should implement the `RequestHandler` interface. \n```go\ntype RequestHandler[TRequest any, TResponse any] interface {\n\tHandle(ctx context.Context, request TRequest) (TResponse, error)\n}\n```\n\nHere we Create `request handler` (command handler and query handler) for our requests, that implements above interface:\n\n``` go\n// Command Handler\ntype CreateProductCommandHandler struct {\n\tproductRepository *repository.InMemoryProductRepository\n}\n\nfunc NewCreateProductCommandHandler(productRepository *repository.InMemoryProductRepository) *CreateProductCommandHandler {\n\treturn \u0026CreateProductCommandHandler{productRepository: productRepository}\n}\n\nfunc (c *CreateProductCommandHandler) Handle(ctx context.Context, command *CreateProductCommand) (*creatingProductDtos.CreateProductCommandResponse, error) {\n\n\tproduct := \u0026models.Product{\n\t\tProductID:   command.ProductID,\n\t\tName:        command.Name,\n\t\tDescription: command.Description,\n\t\tPrice:       command.Price,\n\t\tCreatedAt:   command.CreatedAt,\n\t}\n\n\tcreatedProduct, err := c.productRepository.CreateProduct(ctx, product)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := \u0026creatingProductDtos.CreateProductCommandResponse{ProductID: createdProduct.ProductID}\n\n\treturn response, nil\n}\n```\n\n```go\n// Query Handler\ntype GetProductByIdQueryHandler struct {\n    productRepository *repository.InMemoryProductRepository\n}\n\nfunc NewGetProductByIdQueryHandler(productRepository *repository.InMemoryProductRepository) *GetProductByIdQueryHandler {\n    return \u0026GetProductByIdQueryHandler{productRepository: productRepository}\n}\n\nfunc (c *GetProductByIdQueryHandler) Handle(ctx context.Context, query *GetProductByIdQuery) (*gettingProductDtos.GetProdctByIdQueryResponse, error) {\n\n    product, err := c.productRepository.GetProductById(ctx, query.ProductID)\n    if err != nil {\n        return nil, err\n    }\n\n    response := \u0026gettingProductDtos.GetProdctByIdQueryResponse{\n        ProductID:   product.ProductID,\n        Name:        product.Name,\n        Description: product.Description,\n        Price:       product.Price,\n        CreatedAt:   product.CreatedAt,\n    }\n\n    return response, nil\n}\n```\n\n\u003e Note: In the cases we don't need a response from our request handler, we can use `Unit` type, that actually is an empty struct:.\n\n#### Registering Request Handler to the MediatR\nBefore `sending` or `dispatching` our requests, we should `register` our request handlers to the MediatR.\n\nHere we register our request handlers (command handler and query handler) to the MediatR:\n```go\n// Registering `createProductCommandHandler` request handler for `CreateProductCommand` request to the MediatR\nmediatr.RegisterHandler[*creatingProduct.CreateProductCommand, *creatingProductsDtos.CreateProductCommandResponse](createProductCommandHandler)\n\n// Registering `getProductByIdQueryHandler` request handler for `GetProductByIdQuery` request to the MediatR\nmediatr.RegisterHandler[*gettingProduct.GetProductByIdQuery, *gettingProductDtos.GetProdctByIdQueryResponse](getProductByIdQueryHandler)\n```\n\n#### Sending Request to the MediatR\n\nFinally, send a message through the mediator.\n\nHere we send our requests to the MediatR for dispatching them to the request handlers (command handler and query handler):\n``` go\n// Sending `CreateProductCommand` request to mediatr for dispatching to the `CreateProductCommandHandler` request handler\ncommand := \u0026CreateProductCommand{\n    ProductID:   uuid.NewV4(),\n    Name:        request.name,\n    Description: request.description,\n    Price:       request.price,\n    CreatedAt:   time.Now(),\n}\n\nmediatr.Send[*CreateProductCommand, *creatingProductsDtos.CreateProductCommandResponse](ctx, command)\n```\n\n```go\n// Sending `GetProductByIdQuery` request to mediatr for dispatching to the `GetProductByIdQueryHandler` request handler\nquery := \u0026GetProdctByIdQuery{\n    ProductID:   uuid.NewV4()\n}\n\nmediatr.Send[*GetProductByIdQuery, *gettingProductsDtos.GetProductByIdQueryResponse](ctx, query)\n```\n\n### Notification Strategy\n\nThe `notification` message, can have `multiple handlers` and doesn't have any response, and it can handle an [event notification](https://martinfowler.com/articles/201701-event-driven.html) or notification in event driven architecture.\n\n#### Creating a Notification Message\n\nFor creating a notification (event), that has multiple `handlers` and doesn't have any response, we could create an event notification as a `notification` like this:\n\n```go\n// Event (Notification)\ntype ProductCreatedEvent struct {\n    ProductID uuid.UUID   `json:\"productId\"`\n    Name        string    `json:\"name\"`\n    Description string    `json:\"description\"`\n    Price       float64   `json:\"price\"`\n    CreatedAt   time.Time `json:\"createdAt\"`\n}\n```\nThis event doesn't have any response.\n\n#### Creating Notification Handlers\n\nFor handling our notification, we can create `multiple notification handlers` for each notification event. Each handler should implement the `NotificationHandler` interface.\n```go\ntype NotificationHandler[TNotification any] interface {\n    Handle(ctx context.Context, notification TNotification) error\n}\n```\n\nHere we Create multiple `notification event handler` for our notification, that implements above interface:\n\n```go\n// Notification Event Handler1\ntype ProductCreatedEventHandler1 struct {\n}\n\nfunc (c *ProductCreatedEventHandler1) Handle(ctx context.Context, event *ProductCreatedEvent) error {\n//Do something with the event here !\n    return nil\n}\n```\n\n```go\n// Notification Event Handler2\ntype ProductCreatedEventHandler2 struct {\n}\n\nfunc (c *ProductCreatedEventHandler2) Handle(ctx context.Context, event *ProductCreatedEvent) error {\n//Do something with the event here !\n    return nil\n}\n```\n\n#### Registering Notification Handlers to the MediatR\nBefore `publishing` our notifications, we should `register` our notification handlers to the MediatR.\n\nHere we register our notification handlers to the MediatR:\n```go\n// Registering `notificationHandler1`, `notificationHandler2` notification handler for `ProductCreatedEvent` notification event to the MediatR\nnotificationHandler1 := \u0026ProductCreatedEventHandler1{}\nnotificationHandler2 := \u0026ProductCreatedEventHandler2{}\n\nmediatr.RegisterNotificationHandlers[*events.ProductCreatedEvent](notificationHandler1, notificationHandler2)\n```\n\n#### Publishing Notification to the MediatR\nFinally, publish a notification event through the mediator.\n\nHere we publish our notification to the MediatR for dispatching them to the notification handlers:\n``` go\n// Publishing `ProductCreatedEvent` notification to mediatr for dispatching to the `ProductCreatedEventHandler1`, `ProductCreatedEventHandler2` notification handlers\nproductCreatedEvent := \t\u0026ProductCreatedEvent {\n    ProductID:   createdProduct.ProductID,\n    Name:        createdProduct.Name,\n    Price:       createdProduct.Price,\n    CreatedAt:   createdProduct.CreatedAt,\n    Description: createdProduct.Description,\n}\n\t\nmediatr.Publish[*events.ProductCreatedEvent](ctx, productCreatedEvent)\n```\n\n## ⚒️ Using Pipeline Behaviors\nSometimes we need to add some cross-cutting concerns before after running our request handlers like logging, metrics, circuit breaker, retry, etc. In this case we can use `PipelineBehavior`. It is actually is like a middleware or [decorator pattern](https://refactoring.guru/design-patterns/decorator).\n\nThese behaviors will execute before or after running our request handlers with calling `Send` method for a request on the mediatr.\n\n### Creating Pipeline Behavior\nFor creating a pipeline behaviour we should implement the `PipelineBehavior` interface:\n\n``` go\ntype PipelineBehavior interface {\n\tHandle(ctx context.Context, request interface{}, next RequestHandlerFunc) (interface{}, error)\n}\n```\nThe `request` parameter is the request object passed in through `Send` method of mediatr, while the `next` parameter is a continuation for the next action in the behavior chain and its type is `RequestHandlerFunc`. \n\nHere is an example of a pipeline behavior:\n\n```go\ntype RequestLoggerBehaviour struct {\n}\n\nfunc (r *RequestLoggerBehaviour) Handle(ctx context.Context, request interface{}, next mediatr.RequestHandlerFunc) (interface{}, error) {\n\tlog.Printf(\"logging some stuff before handling the request\")\n\n\tresponse, err := next()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Println(\"logging some stuff after handling the request\")\n\n\treturn response, nil\n}\n```\nIn our defined behavior, we need to call `next` parameter that call next action in the behavior chain, if there aren't any other behaviours `next` will call our `actual request handler` and return the response. We can do something before of after of calling next action in the behavior chain.\n\n### Registering Pipeline Behavior to the MediatR\n\nFor registering our pipeline behavior to the MediatR, we should use `RegisterPipelineBehaviors` method:\n\n```go\nloggerPipeline := \u0026behaviours.RequestLoggerBehaviour{}\nerr = mediatr.RegisterRequestPipelineBehaviors(loggerPipeline)\n```\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmehdihadeli%2FGo-MediatR","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmehdihadeli%2FGo-MediatR","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmehdihadeli%2FGo-MediatR/lists"}