cqrs

package module
v1.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2026 License: MIT Imports: 5 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

cqrs

Go Reference

A lightweight, high-performance, zero-allocation in-memory CQRS and Event Streaming toolkit for Go.

Designed with Clean Architecture and DDD principles in mind. It serves as a non-intrusive glue code layer for your domain models without forcing heavy framework dependencies or leaky abstractions into your core logic.

Highlights

  • Zero Allocations & Zero Copy: Operates directly on standard Go types and interfaces without internal byte-buffering or JSON wrapping overhead.
  • Zero Dependencies: Relies purely on the Go Standard Library.
  • Native Event Streaming: Built-in EventStreamer channel abstraction out-of-the-box for Server-Sent Events (SSE), WebSockets, or background workers.
  • Non-Intrusive (Low Lock-In): Your domain entities, commands, and events remain 100% framework-agnostic. Migrating away or refactoring requires zero changes to core business logic.
  • Thread-Safe & Reliable: Safe for concurrent use with built-in panic recovery for command/event handlers and slow-consumer handling for event streams.

Installation

go get github.com/atmosone/cqrs

Quick Start

  1. Define Domain Types Command, Query, and Event objects are simple Go structs implementing a Type() method.
package main

import (
	"context"
	"time"

	"github.com/atmosone/cqrs"
)

// Command
const CommandTypeCreateNote = cqrs.CommandType("create_note")

type CreateNoteCommand struct {
	Name    string
	Content string
}

func (c CreateNoteCommand) Type() cqrs.CommandType { return CommandTypeCreateNote }

// Event
const EventTypeNoteCreated = cqrs.EventType("note_created")

type NoteCreatedEvent struct {
	ID        string
	Name      string
	CreatedAt time.Time
}

func (e NoteCreatedEvent) Type() cqrs.EventType { return EventTypeNoteCreated }
  1. Implement Handlers Handlers are clean, idiomatic Go functions:
func CreateNoteHandler(ctx context.Context, cmd cqrs.Command) ([]cqrs.Event, error) {
	c := cmd.(CreateNoteCommand)

	// ... execute domain logic / persist to repository ...

	event := NoteCreatedEvent{
		ID:        "note-123",
		Name:      c.Name,
		CreatedAt: time.Now(),
	}

	return []cqrs.Event{event}, nil
}
  1. Bootstrap Application & Serve SSE
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"

	"github.com/atmosone/cqrs"
)

func main() {
	app := cqrs.New()
	defer app.Close()

	// Register Command Handler
	app.OnCommand(CommandTypeCreateNote, CreateNoteHandler)

	// HTTP Endpoint: Execute Command
	http.HandleFunc("POST /notes", func(w http.ResponseWriter, r *http.Request) {
		var cmd CreateNoteCommand
		if err := json.NewDecoder(r.Body).Decode(&cmd); err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if err := app.HandleCommand(r.Context(), cmd); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
	})

	// HTTP Endpoint: Stream Real-Time Events via SSE
	http.HandleFunc("GET /events", func(w http.ResponseWriter, r *http.Request) {
		flusher, ok := w.(http.Flusher)
		if !ok {
			http.Error(w, "Streaming unsupported", http.StatusBadRequest)
			return
		}

		w.Header().Set("Content-Type", "text/event-stream")
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Connection", "keep-alive")

		stream, err := app.EventStream(r.Context())
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}

		for event := range stream {
			fmt.Fprintf(w, "event: %s\ndata: ", event.Type().String())
			_ = json.NewEncoder(w).Encode(event)
			fmt.Fprint(w, "\n")
			flusher.Flush()
		}
	})

	http.ListenAndServe(":8080", nil)
}

Projections

Register projections to build read models asynchronously or synchronize state:

type AuditProjection struct{}

func (p *AuditProjection) Types() []cqrs.EventType {
	return []cqrs.EventType{EventTypeNoteCreated}
}

func (p *AuditProjection) HandleEvent(ctx context.Context, event cqrs.Event) error {
	// Update read storage, elasticsearch, cache, etc.
	return nil
}

// Register projection
app.Build(&AuditProjection{})

Benchmarks

Because the library executes direct map lookups and standard Go channel dispatches without intermediate byte allocations:

Command Routing Delay: ~10-15 ns/op Memory Allocations: 0 B/op (framework core)

License MIT

Documentation

Overview

Package cqrs provides a lightweight, zero-allocation, thread-safe in-memory CQRS (Command Query Responsibility Segregation) and Event Streaming toolkit for Go.

Index

Constants

This section is empty.

Variables

View Source
var ErrUnimplementedHandler = errors.New("cqrs: unimplemented handler")

ErrUnimplementedHandler - error value for unimplemented handler cases.

Functions

This section is empty.

Types

type App

App is the CQRS application facade interface.

func New added in v1.2.0

func New() App

New returns new CQRS application facade instance.

type Command

type Command interface {
	Type() CommandType // Type returns [CommandType] value.
}

Command is the interface implemented by types that contains instructions for changing the state of the system (creating, updating, or deleting data).

type CommandHandler

type CommandHandler interface {
	// HandleCommand implements [CommandHandlerFunc] but without [Event] collection returning.
	HandleCommand(context.Context, Command) error
}

CommandHandler is the interface implemented by types that can handle Command.

type CommandHandlerFunc

type CommandHandlerFunc func(context.Context, Command) ([]Event, error)

CommandHandlerFunc is the type for functions that can handle Command and return Event collection. Returns non-nil [error] if Command cannot be handled.

type CommandRegistry added in v1.3.0

type CommandRegistry interface {
	OnCommand(CommandType, CommandHandlerFunc) // OnCommand registers [CommandHandlerFunc] for [CommandType] value.
}

CommandRegistry is the interface implemented by types that can register CommandHandlerFunc for CommandType value.

type CommandType

type CommandType string

CommandType is the string alias for Command type declaration.

func (CommandType) String

func (ct CommandType) String() string

String returns base CommandType string value.

type Event

type Event interface {
	Type() EventType // Type returns [EventType] value.
}

Event is the interface implemented by types that contains data describes system state changes.

type EventHandler

type EventHandler interface {
	HandleEvent(context.Context, Event) error // HandleEvent implements [EventHandlerFunc].
}

EventHandler is the interface implemented by types that can handle Event.

type EventHandlerFunc

type EventHandlerFunc func(context.Context, Event) error

EventHandlerFunc is the type for functions that can handle Event Returns non-nil [error] if Event cannot be handled.

type EventRegistry added in v1.3.0

type EventRegistry interface {
	OnEvent(EventType, EventHandlerFunc) // OnEvent registers [EventHandlerFunc] for [EventType] value.
}

EventRegistry is the interface implemented by types that can register EventHandlerFunc for EventType value.

type EventStreamer added in v1.3.0

type EventStreamer interface {
	EventStream(context.Context) (<-chan Event, error)
}

EventStreamer is the interface implemented by types that can stream Event via channel.

type EventType

type EventType string

EventType is the string alias for Event type declaration.

func (EventType) String

func (et EventType) String() string

String returns base EventType string value.

type Projection added in v1.3.0

type Projection interface {
	EventHandler
	Types() []EventType // Types returns collection of [EventType] which [Projection] can handle.
}

Projection is the interface implemented by types that can collect and transform system Event or operational data into convenient, denormalized models optimized for fast reading. Projection is the polymorphic EventHandler with own Event routing.

type ProjectionBuilder added in v1.3.0

type ProjectionBuilder interface {
	// Build registers [Projection.HandleEvent] method for each in [Projection.Types] [EventType] value.
	Build(Projection)
}

ProjectionBuilder is the interface implemented by types that can register Projection for it's building.

type Query

type Query interface {
	Type() QueryType // Type returns [QueryType] value.
}

Query is the interface implemented by types that contains instructions for read-only operations without changes in system state.

type QueryHandler

type QueryHandler interface {
	HandleQuery(context.Context, Query) (Result, error) // HandleQuery implements [QueryHandlerFunc].
}

QueryHandler is the interface implemented by types that can handle Query.

type QueryHandlerFunc

type QueryHandlerFunc func(context.Context, Query) (Result, error)

QueryHandlerFunc is the type for functions that can handle Query and return Result.Returns non-nil [error] if Query cannot be handled.

type QueryRegistry added in v1.3.0

type QueryRegistry interface {
	OnQuery(QueryType, QueryHandlerFunc) // OnQuery registers [QueryHandlerFunc] for [QueryType] value.
}

QueryRegistry is the interface implemented by types that can register QueryHandlerFunc for QueryType value.

type QueryType

type QueryType string

QueryType is the string alias for Query type declaration.

func (QueryType) String

func (qt QueryType) String() string

String returns base QueryType string value.

type Result

type Result any

Result is the interface implemented by types that contains read-only data describes current system state.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL