go-bricks

module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Sep 17, 2025 License: MIT

README

GoBricks

Modern building blocks for Go microservices. GoBricks brings together configuration, HTTP, messaging, database, logging and observability primitives that teams need to ship production-grade services fast.

CI Go Report Card codecov Go Reference


Table of Contents

  1. Why GoBricks?
  2. Feature Overview
  3. Quick Start
  4. Configuration
  5. Modules and Application Structure
  6. HTTP Server
  7. Messaging
  8. Database
  9. Observability and Operations
  10. Examples
  11. Contributing
  12. License

Why GoBricks?

  • Production-ready defaults for the boring-but-essential pieces (server, logging, configuration, tracing).
  • Composable module system that keeps HTTP, database, and messaging concerns organized.
  • Mission-critical integrations (PostgreSQL, Oracle, RabbitMQ, Flyway) with unified ergonomics.
  • Extensible design that works with modern Go idioms and the wider ecosystem.

Feature Overview

  • Modular architecture with explicit dependencies and lifecycle hooks.
  • Echo-based HTTP server with typed handlers, standardized response envelopes, and middleware batteries.
  • AMQP messaging registry for RabbitMQ that orchestrates exchanges, queues, publishers, and consumers.
  • Configuration loader built on Koanf that merges defaults, YAML, and environment variables.
  • Database toolkit with PostgreSQL and Oracle drivers, query builders, and health checks.
  • Flyway migration integration for schema evolution.
  • Structured logging and observability with trace propagation, request instrumentation, and health endpoints.

Quick Start

Install
go mod init your-service
go get github.com/gaborage/go-bricks@latest
Bootstrap an application
// cmd/main.go
package main

import (
    "log"

    "github.com/gaborage/go-bricks/app"
    "github.com/gaborage/go-bricks/config"
)

func main() {
    cfg, err := config.Load()
    if err != nil {
        log.Fatal(err)
    }

    framework, err := app.NewWithConfig(cfg, nil)
    if err != nil {
        log.Fatal(err)
    }

    // Register modules here: framework.RegisterModule(newExampleModule())

    if err := framework.Run(); err != nil {
        log.Fatal(err)
    }
}
Configuration file
app:
  name: "my-service"
  version: "v1.0.0"
  env: "development"
  rate_limit: 200

server:
  port: 8080

database:
  type: postgresql
  host: localhost
  port: 5432
  database: mydb
  username: postgres
  password: password

log:
  level: info
  pretty: true

GoBricks loads defaults → config.yamlconfig.<env>.yaml → environment variables. app.env controls the environment suffix and defaults to development.


Configuration

Accessing values

Only the essential accessors are exposed:

cfg, _ := config.Load()

host := cfg.GetString("server.host", "0.0.0.0")
port := cfg.GetInt("server.port", 8080)
pretty := cfg.GetBool("log.pretty")
Required values with validation
apiKey, err := cfg.GetRequiredString("custom.api.key")
if err != nil {
    return fmt.Errorf("missing api key: %w", err)
}
Custom namespace

Custom application parameters live under custom.*:

enabled := cfg.GetBool("custom.feature.flag")
maxItems := cfg.GetInt("custom.max.items", 100)

// Convert string durations manually
rawTimeout := cfg.GetString("custom.service.timeout")
timeout, err := time.ParseDuration(rawTimeout)

// Unmarshal structured custom config
var custom struct {
    FeatureFlag bool `koanf:"feature.flag"`
    Service struct {
        Endpoint string `koanf:"endpoint"`
        Timeout  string `koanf:"timeout"`
    } `koanf:"service"`
}
_ = cfg.Unmarshal("custom", &custom)

See examples/params/main.go for a complete walkthrough.

Overriding via environment

Environment variables override everything using uppercase and underscores:

APP_NAME=my-service
DATABASE_HOST=prod-db.company.com
CUSTOM_FEATURE_FLAG=true

Modules and Application Structure

Module interface
type Module interface {
    Name() string
    Init(deps *ModuleDeps) error
    RegisterRoutes(hr *server.HandlerRegistry, e *echo.Echo)
    RegisterMessaging(registry *messaging.Registry)
    Shutdown() error
}

ModuleDeps injects shared services:

type ModuleDeps struct {
    DB        database.Interface
    Logger    logger.Logger
    Messaging messaging.Client
    Config    *config.Config
}
Registering a module
func register(framework *app.App) error {
    return framework.RegisterModule(&users.Module{})
}

Init is called once to capture dependencies, RegisterRoutes attaches HTTP handlers, RegisterMessaging declares AMQP infrastructure, and Shutdown releases resources.


HTTP Server

  • Based on Echo v4 with middleware stack (logging, recovery, rate limiting, CORS).
  • Request binding/validation: define request structs with tags (path, query, header, validate).
  • Response envelope ensures consistent {data:…, meta:…} payloads.
  • Typed handler signatures simplify status codes:
func (h *Handler) createUser(req CreateReq, ctx server.HandlerContext) (server.Result[User], server.IAPIError) {
    user := h.svc.Create(req)
    return server.Created(user), nil
}

Messaging

AMQP support via RabbitMQ:

  • Declare exchanges and queues once using the shared registry.
  • Register publishers/consumers during module initialization.
  • Health / readiness hooks integrate with the main app lifecycle.
func (m *Module) RegisterMessaging(reg *messaging.Registry) {
    reg.DeclareExchange("user.events", "topic")
    reg.RegisterConsumer("user.events", "user.created", handler)
}

Database

PostgreSQL / Oracle support

Configure under database.* and use the provided factory to create connections. The query builder handles dialect differences (placeholders, quoting) and health checks feed into the readiness probe.

Flyway migrations

GoBricks ships with a Flyway integration that runs migrations via CLI while injecting database credentials from configuration.

migrator := migration.NewFlywayMigrator(cfg, log)
_ = migrator.Migrate(ctx, nil)

Observability and Operations

  • Structured logging via Zerolog.
  • Tracing propagates W3C traceparent headers.
  • Metrics capture HTTP/messaging/database timings.
  • Health endpoints: /health (liveness) and /ready (readiness with DB/messaging checks).
  • Graceful shutdown coordinates servers, consumers, and background workers.

Examples

Explore the examples/ folder:

  • http/handlers – typed HTTP handler module
  • http/client – fluent HTTP client with retries and interceptors
  • oracle – Oracle insert with reserved column quoting
  • params – custom configuration namespace demo
  • trace-propagation – W3C tracing demonstration

Contributing

Issues and pull requests are welcome! See CONTRIBUTING.md for coding standards, tooling, and workflow.


License

MIT © Contributors


Built with ❤️ for the Go community.

Directories

Path Synopsis
Package app provides the core application structure and lifecycle management.
Package app provides the core application structure and lifecycle management.
Package database provides cross-database query building utilities
Package database provides cross-database query building utilities
examples
http/client command
http/handlers command
Package main demonstrates the enhanced handler system usage.
Package main demonstrates the enhanced handler system usage.
oracle command
params command
trace-propagation command
Package main demonstrates the HTTP client's automatic trace ID propagation
Package main demonstrates the HTTP client's automatic trace ID propagation
internal
Package logger provides logging functionality with zerolog adapter
Package logger provides logging functionality with zerolog adapter
Package messaging provides a unified interface for message queue operations.
Package messaging provides a unified interface for message queue operations.
Package migration provides integration with Flyway for database migrations
Package migration provides integration with Flyway for database migrations
Package server provides enhanced HTTP handler functionality with type-safe request/response handling.
Package server provides enhanced HTTP handler functionality with type-safe request/response handling.

Jump to

Keyboard shortcuts

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