humus

package module
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2025 License: MIT Imports: 11 Imported by: 2

README

Humus

Go Reference Go Report Card Coverage build

A modular Go framework for building production-ready REST APIs, gRPC services, and batch jobs with built-in observability, health checks, and graceful shutdown.

Built on top of Bedrock, Humus provides standardized patterns and automatic instrumentation to help you focus on business logic while maintaining best practices.

Quick Start

package main

import (
    "context"
    "net/http"

    "github.com/z5labs/humus/rest"
    "github.com/z5labs/humus/rest/rpc"
)

type HelloResponse struct {
    Message string `json:"message"`
}

func main() {
    rest.Run(rest.YamlSource("config.yaml"), Init)
}

func Init(ctx context.Context, cfg rest.Config) (*rest.Api, error) {
    api := rest.NewApi("Hello API", "1.0.0")

    handler := rpc.ProducerFunc[HelloResponse](func(ctx context.Context) (*HelloResponse, error) {
        return &HelloResponse{Message: "Hello, World!"}, nil
    })

    rest.Handle(http.MethodGet, rest.BasePath("/hello"), rpc.ProduceJson(handler))
    return api, nil
}

Your API is now running with:

  • Automatic OpenAPI documentation at /openapi.json
  • Health endpoints at /health/liveness and /health/readiness
  • OpenTelemetry tracing and metrics
  • Graceful shutdown handling

Features

🌐 REST Services
  • OpenAPI 3.0 - Automatic spec generation from Go types
  • Type-safe handlers - Compile-time request/response validation
  • Built-in authentication - JWT, API keys, Basic auth, OAuth2
  • Parameter validation - Query params, headers, path params with regex support
🔌 gRPC Services
  • Auto-instrumentation - OpenTelemetry interceptors built-in
  • Health service - Automatic gRPC health checks
  • Service registration - Simple, familiar gRPC patterns
⚙️ Job/Batch Services
  • One-off execution - Run jobs with observability and lifecycle management
  • Simple interface - Just implement Handle(ctx context.Context) error
📊 Observability
  • OpenTelemetry SDK - Traces, metrics, and logs out of the box
  • Structured logging - slog integration with context propagation
  • Health monitoring - Composable health check patterns

Installation

go get github.com/z5labs/humus

Documentation

📚 Full Documentation - Comprehensive guides, examples, and API reference

Examples

Check out the examples directory for complete, runnable examples:

AI Coding Agent Instructions

If you're using an AI coding agent (like GitHub Copilot, Cursor, etc.), copy the relevant instruction files from the instructions/ directory to your project repository (e.g., .github/). These files provide your AI assistant with Humus framework best practices, project structure patterns, and common pitfalls to avoid.

Available instruction files:

Copy humus-common.instructions.md along with the file(s) specific to your application type.

Requirements

  • Go 1.24 or later

License

Released under the MIT License.

Documentation

Overview

Package humus provides a base config and abstraction for running apps.

Package humus provides utilities for building and running bedrock applications with integrated OpenTelemetry logging and error handling.

The package simplifies application lifecycle management by providing:

  • OpenTelemetry-integrated structured logging via Logger and LogHandler
  • Application runners with customizable error handling via Runner
  • Standard patterns for building and running bedrock applications

Basic Usage

Create a logger with OpenTelemetry integration:

log := humus.Logger("myapp")
log.Info("application started")

Build and run an application with error handling:

runner := humus.NewRunner(
    appBuilder,
    humus.OnError(humus.ErrorHandlerFunc(func(err error) {
        log.Printf("Error: %v", err)
    })),
)
runner.Run(context.Background(), config)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigSource added in v0.9.0

func ConfigSource(r io.Reader) bedrockcfg.Source

ConfigSource standardizes the template for configuration of humus applications. The io.Reader is expected to be YAML with support for Go templating. Currently, only 2 template functions are supported:

  • env - this allows environment variables to be substituted into the YAML
  • default - define a default value in case the original value is nil

func DefaultConfig added in v0.4.0

func DefaultConfig() bedrockcfg.Source

DefaultConfig returns the default config source which corresponds to the Config type.

func LogHandler added in v0.12.0

func LogHandler(name string) slog.Handler

LogHandler creates a new slog.Handler with OpenTelemetry integration. This is useful when you need to create a custom logger with specific handler options while maintaining OpenTelemetry integration.

Example:

handler := humus.LogHandler("myapp")
logger := slog.New(handler)

func Logger

func Logger(name string) *slog.Logger

Logger creates a new structured logger with OpenTelemetry integration. The logger automatically bridges log records to OpenTelemetry, enabling correlation between logs and traces.

The name parameter identifies the logger and appears in log output, making it easier to filter and identify log sources.

Example:

log := humus.Logger("rest-api")
log.Info("server started", slog.Int("port", 8080))
log.Error("connection failed", slog.String("error", err.Error()))

Types

type Config

type Config struct {
	OTel config.OTel `config:"otel"`
}

Config defines the common configuration for all humus based applications.

func (Config) InitializeOTel added in v0.5.0

func (cfg Config) InitializeOTel(ctx context.Context) error

InitializeOTel implements the [appbuilder.OTelInitializer] interface.

type ErrorHandler added in v0.5.0

type ErrorHandler interface {
	HandleError(error)
}

ErrorHandler defines custom error handling logic for a Runner. The handler is called when errors occur during application building or running, allowing applications to implement custom error logging, reporting, or recovery.

By default, the runner logs errors as JSON to stdout.

type ErrorHandlerFunc added in v0.5.0

type ErrorHandlerFunc func(error)

ErrorHandlerFunc is a function adapter that implements ErrorHandler. It allows regular functions to be used as error handlers.

Example:

handler := humus.ErrorHandlerFunc(func(err error) {
    log.Printf("Application error: %v", err)
    metrics.RecordError(err)
})

func (ErrorHandlerFunc) HandleError added in v0.5.0

func (f ErrorHandlerFunc) HandleError(err error)

HandleError implements the ErrorHandler interface.

type Runner added in v0.5.0

type Runner[T any] struct {
	// contains filtered or unexported fields
}

Runner orchestrates the complete lifecycle of a bedrock.App. It handles both the build phase (creating the app from configuration) and the run phase (executing the app), with customizable error handling for each stage.

The runner uses the provided bedrock.AppBuilder to construct the application and invokes the configured ErrorHandler if any errors occur.

func NewRunner added in v0.5.0

func NewRunner[T any](builder bedrock.AppBuilder[T], opts ...RunnerOption) Runner[T]

NewRunner creates a new Runner with the specified app builder and options.

By default, the runner logs errors as JSON to stdout. This behavior can be customized using the OnError option.

Type parameter T represents the configuration type that will be passed to the app builder during the build phase.

Example:

builder := appbuilder.FromConfig(myBuilder)
runner := humus.NewRunner(
    builder,
    humus.OnError(humus.ErrorHandlerFunc(func(err error) {
        fmt.Fprintf(os.Stderr, "Fatal error: %v\n", err)
        os.Exit(1)
    })),
)

func (Runner[T]) Run added in v0.5.0

func (r Runner[T]) Run(ctx context.Context, cfg T)

Run executes the complete application lifecycle using the provided configuration.

The method performs two main steps:

  1. Build: Constructs the application using the builder and configuration
  2. Run: Executes the built application

If an error occurs during either step, the configured error handler is invoked. The method does not return errors directly; instead, all error handling is delegated to the ErrorHandler.

The context is passed to both the build and run phases, allowing for proper cancellation and deadline handling throughout the application lifecycle.

Example:

config := loadConfig()
runner := humus.NewRunner(appBuilder)
runner.Run(context.Background(), config)

type RunnerOption added in v0.5.0

type RunnerOption interface {
	ApplyRunnerOption(*RunnerOptions)
}

RunnerOption configures a Runner. Use OnError to customize error handling behavior.

func OnError added in v0.5.0

func OnError(eh ErrorHandler) RunnerOption

OnError configures a custom ErrorHandler for a Runner. The error handler is invoked whenever the runner encounters an error during application build or execution.

Example:

runner := humus.NewRunner(
    builder,
    humus.OnError(humus.ErrorHandlerFunc(func(err error) {
        log.Fatal(err)
    })),
)

type RunnerOptions added in v0.5.0

type RunnerOptions struct {
	// contains filtered or unexported fields
}

RunnerOptions holds configuration parameters for a Runner. These options control how the runner handles errors during application build and execution phases.

Directories

Path Synopsis
Package config provides configuration schemas for OpenTelemetry instrumentation in Humus applications.
Package config provides configuration schemas for OpenTelemetry instrumentation in Humus applications.
example
grpc/petstore command
rest/htmx command
rest/petstore command
Package grpc supports creating gRPC applications.
Package grpc supports creating gRPC applications.
Package health provides utilities for monitoring the healthiness of an application.
Package health provides utilities for monitoring the healthiness of an application.
Package job provides support for creating job based services.
Package job provides support for creating job based services.
Package queue provides support for creating message queue processing services.
Package queue provides support for creating message queue processing services.
kafka
Package kafka provides Kafka runtime implementations for the Humus queue framework.
Package kafka provides Kafka runtime implementations for the Humus queue framework.
Package rest provides a framework for building OpenAPI-compliant RESTful HTTP applications.
Package rest provides a framework for building OpenAPI-compliant RESTful HTTP applications.

Jump to

Keyboard shortcuts

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