elgon

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2026 License: GPL-3.0 Imports: 13 Imported by: 0

README

elgon

Go Reference Go Report Card

elgon is a performance-oriented, API-first Go web framework built on top of net/http. It provides production-focused defaults while keeping APIs explicit, modular, and easy to test.

Why elgon

  • Fast routing with static, param, and wildcard path matching
  • Low-overhead middleware pipeline
  • Centralized typed error handling
  • Built-in health and metrics support
  • OpenAPI generation and Swagger UI serving
  • Config loading from environment and JSON files
  • Auth support (JWT, RBAC guards, OAuth2/OIDC helpers)
  • Database adapters, migrations, and background jobs
  • CLI commands for common development workflows

Core Packages

  • elgon: app lifecycle, router, context, handler/middleware contracts
  • middleware: recover, request ID, logger, CORS, body limit, secure headers
  • config: strict typed config loading (env, default, required tags)
  • observability: metrics middleware/endpoint and tracing interfaces
  • openapi: route-driven OpenAPI generation with schema/tag annotations
  • auth: JWT auth, RBAC middleware, OAuth2/OIDC helpers
  • db: adapter abstractions and SQL adapter helpers
  • orm: optional typed repositories over db.Adapter
  • migrate: SQL migration loading and engine (up, down, status)
  • jobs: in-memory queue, SQL distributed backend, Redis/Kafka queue interfaces

Installation

go get github.com/dmesha3/elgon

Quick Start

package main

import (
	"log"
	"log/slog"
	"os"

	"github.com/dmesha3/elgon"
	"github.com/dmesha3/elgon/middleware"
	"github.com/dmesha3/elgon/observability"
	"github.com/dmesha3/elgon/openapi"
)

func main() {
	app := elgon.New(elgon.Config{Addr: ":8080"})
	metrics := observability.NewMetrics()

	app.Use(
		middleware.Recover(),
		middleware.RequestID(),
		middleware.Logger(slog.New(slog.NewJSONHandler(os.Stdout, nil))),
		metrics.Middleware(),
	)

	app.GET("/users/:id", func(c *elgon.Ctx) error {
		return c.JSON(200, map[string]string{"id": c.Param("id")})
	})

	metrics.RegisterRoute(app, "/metrics")
	openapi.NewGenerator("Example API", elgon.Version).Register(app, "/openapi.json", "/docs")

	if err := app.Run(); err != nil {
		log.Fatal(err)
	}
}

Demo Application

A complete reference implementation is available at:

  • examples/demo-app
  • examples/prod-api

Run it with:

cd examples/demo-app
go mod tidy
go run ./cmd/api

Production sample:

cd examples/prod-api
go mod tidy
go run ./cmd/api

CLI

elgon includes a project CLI under cmd/elgon.

go run ./cmd/elgon --help

Available command groups include new, dev, test, bench, migrate, and openapi.

Developer Run Modes

Standard development run:

make dev

Hot reload (file watcher) with air:

make dev HOT_RELOAD=1

elgon dev --hot-reload will use local air when available, and otherwise falls back to go run github.com/air-verse/air@latest.

You can also use the CLI directly:

go run ./cmd/elgon dev --hot-reload

Testing and Benchmarks

go test ./...
make bench-ci
make bench

DB integration tests are env-driven and can be enabled with:

  • ELGON_DB_TEST_DRIVER
  • ELGON_DB_TEST_DSN

Optional Adapters

Concrete Redis and Kafka adapters are provided behind the adapters build tag:

  • jobs/redisadapter (go-redis)
  • jobs/kafkaadapter (segmentio/kafka-go)

Build/test with adapters:

go test -tags adapters ./...
go build -tags adapters ./...

Optional ORM

adapter, _ := db.OpenSQLite(db.SQLiteConfig{})
app := elgon.New(elgon.Config{Addr: ":8080"})
app.SetSQL(adapter)
app.SetORMDialect("sqlite")

_, err := app.ORM().Table("users").Create(context.Background(), orm.Values{
	"id":    "usr_1",
	"email": "kazimoto17@proton.me",
	"name":  "Meshack",
})
if err != nil {
	log.Fatal(err)
}

user, err := app.ORM().Table("users").FindOne(context.Background(), orm.FindOptions{
	Columns: []string{"id", "email", "name"},
	Where:   orm.Where{"id": "usr_1"},
})
if err != nil {
	log.Fatal(err)
}
_ = user["email"]

_, _ = app.SQL().ExecContext(context.Background(), "UPDATE users SET name=? WHERE id=?", "M", "usr_1")

Docs

  • API stability: docs/API_STABILITY.md
  • Module docs:
    • docs/modules/auth.md
    • docs/modules/openapi.md
    • docs/modules/jobs.md
    • docs/modules/migrate.md
    • docs/modules/orm.md
  • Installation: INSTALL.md
  • Releasing: docs/RELEASING.md

Documentation

Overview

Package elgon is a performance-oriented, API-first web framework for Go.

Elgon is built on top of the standard net/http package and focuses on delivering production-ready features with minimal overhead. It provides a clean and explicit API for building scalable backend services.

Features:

- Fast and flexible HTTP router (static, param, wildcard routes) - Composable middleware pipeline - Typed request context (Ctx) - Centralized error handling - Built-in observability (metrics & tracing interfaces) - OpenAPI generation with Swagger UI - Authentication utilities (JWT, RBAC, OAuth2/OIDC) - Database adapters, ORM helpers, and migrations - Background jobs with pluggable queue backends

Basic Usage:

app := elgon.New(elgon.Config{Addr: ":8080"})

app.GET("/", func(c *elgon.Ctx) error {
	return c.JSON(200, map[string]string{"message": "hello"})
})

if err := app.Run(); err != nil {
	log.Fatal(err)
}

Middleware:

app.Use(
	middleware.Recover(),
	middleware.RequestID(),
	middleware.Logger(...),
)

Observability:

metrics := observability.NewMetrics()
app.Use(metrics.Middleware())
metrics.RegisterRoute(app, "/metrics")

OpenAPI:

openapi.NewGenerator("My API", elgon.Version).
	Register(app, "/openapi.json", "/docs")

Project Structure:

- elgon: core application, router, and context - middleware: HTTP middleware implementations - config: configuration loading utilities - observability: metrics and tracing - openapi: OpenAPI generation and docs UI - auth: authentication and authorization helpers - db: database adapters - orm: higher-level database abstractions - migrate: migration engine - jobs: background job processing

For more examples and guides, see the README and examples directory.

Index

Constants

View Source
const (
	CodeBadRequest   = "BAD_REQUEST"
	CodeUnauthorized = "UNAUTHORIZED"
	CodeForbidden    = "FORBIDDEN"
	CodeNotFound     = "NOT_FOUND"
	CodeConflict     = "CONFLICT"
	CodeInternal     = "INTERNAL_ERROR"
)
View Source
const (
	Version = "0.2.3"
)

Variables

This section is empty.

Functions

func ErrBadRequest

func ErrBadRequest(msg string, details any) error

func ErrConflict

func ErrConflict(msg string) error

func ErrForbidden

func ErrForbidden(msg string) error

func ErrInternal

func ErrInternal(msg string) error

func ErrNotFound

func ErrNotFound(msg string) error

func ErrUnauthorized

func ErrUnauthorized(msg string) error

Types

type App

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

App is the main elgon application.

func New

func New(cfg Config) *App

func (*App) DELETE

func (a *App) DELETE(path string, h HandlerFunc, mw ...Middleware)

func (*App) GET

func (a *App) GET(path string, h HandlerFunc, mw ...Middleware)

func (*App) Group

func (a *App) Group(prefix string, mw ...Middleware) *Group

func (*App) Named

func (a *App) Named(name string) *NamedRoute

func (*App) ORM

func (a *App) ORM() *orm.Client

ORM returns a typed ORM client backed by the configured SQL adapter.

func (*App) PATCH

func (a *App) PATCH(path string, h HandlerFunc, mw ...Middleware)

func (*App) POST

func (a *App) POST(path string, h HandlerFunc, mw ...Middleware)

func (*App) PUT

func (a *App) PUT(path string, h HandlerFunc, mw ...Middleware)

func (*App) Plugins

func (a *App) Plugins() []string

Plugins returns the list of registered plugin names.

func (*App) RegisterPlugins

func (a *App) RegisterPlugins(plugins ...Plugin) error

RegisterPlugins initializes and registers one or more plugins.

func (*App) Routes

func (a *App) Routes() []RouteInfo

Routes returns a copy of the registered route table.

func (*App) Run

func (a *App) Run() error

func (*App) SQL

func (a *App) SQL() db.Adapter

SQL returns the configured raw SQL adapter.

func (*App) ServeHTTP

func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*App) SetORMDialect

func (a *App) SetORMDialect(dialect string)

SetORMDialect sets placeholder behavior for app.ORM() repositories.

func (*App) SetSQL

func (a *App) SetSQL(adapter db.Adapter)

SetSQL sets the application's raw SQL adapter used by SQL and ORM accessors.

func (*App) SetValidator

func (a *App) SetValidator(v Validator)

func (*App) Use

func (a *App) Use(mw ...Middleware)

type Config

type Config struct {
	Addr              string
	ReadTimeout       time.Duration
	WriteTimeout      time.Duration
	IdleTimeout       time.Duration
	ShutdownTimeout   time.Duration
	DisableHealthz    bool
	EnableMetricsStub bool
}

Config defines server runtime options.

type Ctx

type Ctx struct {
	Writer  http.ResponseWriter
	Request *http.Request
	// contains filtered or unexported fields
}

Ctx wraps request and response objects plus request-scoped helpers.

func (*Ctx) BindJSON

func (c *Ctx) BindJSON(dst any) error

func (*Ctx) Get

func (c *Ctx) Get(key string) (any, bool)

func (*Ctx) Header

func (c *Ctx) Header(name string) string

func (*Ctx) JSON

func (c *Ctx) JSON(status int, body any) error

func (*Ctx) Param

func (c *Ctx) Param(name string) string

func (*Ctx) Query

func (c *Ctx) Query(name string) string

func (*Ctx) RoutePattern

func (c *Ctx) RoutePattern() string

func (*Ctx) Set

func (c *Ctx) Set(key string, value any)

func (*Ctx) Text

func (c *Ctx) Text(status int, msg string) error

func (*Ctx) Validate

func (c *Ctx) Validate(v any) error

type ErrorBody

type ErrorBody struct {
	Code      string `json:"code"`
	Message   string `json:"message"`
	Details   any    `json:"details,omitempty"`
	RequestID string `json:"request_id,omitempty"`
}

ErrorBody describes API error details.

type ErrorResponse

type ErrorResponse struct {
	Error ErrorBody `json:"error"`
}

ErrorResponse is the default structured error payload.

type Group

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

Group is a route group with a shared prefix and middleware.

func (*Group) DELETE

func (g *Group) DELETE(path string, h HandlerFunc, mw ...Middleware)

func (*Group) GET

func (g *Group) GET(path string, h HandlerFunc, mw ...Middleware)

func (*Group) Group

func (g *Group) Group(prefix string, mw ...Middleware) *Group

func (*Group) PATCH

func (g *Group) PATCH(path string, h HandlerFunc, mw ...Middleware)

func (*Group) POST

func (g *Group) POST(path string, h HandlerFunc, mw ...Middleware)

func (*Group) PUT

func (g *Group) PUT(path string, h HandlerFunc, mw ...Middleware)

type HTTPError

type HTTPError struct {
	Code    string
	Message string
	Details any
	Status  int
}

HTTPError is a typed application error mapped by the central handler.

func (*HTTPError) Error

func (e *HTTPError) Error() string

type HandlerFunc

type HandlerFunc func(*Ctx) error

HandlerFunc handles an HTTP request and returns an error for centralized handling.

type Middleware

type Middleware func(HandlerFunc) HandlerFunc

Middleware wraps a handler with extra behavior.

type NamedRoute

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

NamedRoute allows registering a route and associating it with a name.

func (*NamedRoute) DELETE

func (n *NamedRoute) DELETE(path string, h HandlerFunc, mw ...Middleware)

func (*NamedRoute) GET

func (n *NamedRoute) GET(path string, h HandlerFunc, mw ...Middleware)

func (*NamedRoute) PATCH

func (n *NamedRoute) PATCH(path string, h HandlerFunc, mw ...Middleware)

func (*NamedRoute) POST

func (n *NamedRoute) POST(path string, h HandlerFunc, mw ...Middleware)

func (*NamedRoute) PUT

func (n *NamedRoute) PUT(path string, h HandlerFunc, mw ...Middleware)

type Plugin

type Plugin interface {
	Name() string
	Init(*App) error
}

Plugin defines an extension hook that can configure the app at startup.

type RouteInfo

type RouteInfo struct {
	Method string
	Path   string
}

RouteInfo describes a registered route method and path.

type Validator

type Validator interface {
	Validate(any) error
}

Validator validates a value and returns an error if invalid.

Directories

Path Synopsis
cmd
api command
elgon command
kafkaadapter
Package kafkaadapter provides kafka-go implementations of jobs.KafkaProducer and jobs.KafkaConsumer.
Package kafkaadapter provides kafka-go implementations of jobs.KafkaProducer and jobs.KafkaConsumer.
redisadapter
Package redisadapter provides a go-redis implementation of jobs.RedisClient.
Package redisadapter provides a go-redis implementation of jobs.RedisClient.

Jump to

Keyboard shortcuts

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