gframework

module
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2026 License: MIT

README ΒΆ

gframework

gframework is a production-ready Go microservices framework providing essential building blocks for scalable backend services: an Echo v5 HTTP server, Keycloak/JWT authentication, PostgreSQL, Redis/Valkey messaging, S3-compatible object storage, and coordinated service lifecycle management.

CI Go Version License

πŸ“¦ Installation

go get github.com/andyle182810/gframework

🧩 Packages

Package Description
httpserver Echo v5 REST server with request logging, body limits, validation, error handling, CORS, and secure timeout defaults
runner Application lifecycle manager: tiered startup (infrastructure β†’ core), graceful shutdown, failure detection
middleware JWT validation (JWKS), internal service-to-service auth, request ID, request logging, role checks, error handler
jwks JWKS key function with background refresh and rate-limited unknown-KID lookups
authtoken Keycloak service-account token cache with automatic refresh
keycloak Keycloak admin client (users, realm roles) and UMA 2.0 permission checks
httpclient Type-safe JSON REST client with bearer-token injection, request-ID propagation, response size limits
postgres pgx/v5 connection pool with tracing, session timeouts, migrations, transactions, retry, batching
valkey Valkey/Redis client wrapper with TLS, pooling, and health checks
redispub / redissub Redis Streams pub/sub (Watermill) with retries, execution timeouts, and dead-letter queues
taskqueue Redis-backed task queue with delayed execution and stale-task recovery
distlock Redis distributed locks (fail-hard and fail-silent modes)
workerpool Tick-driven worker pool for periodic background jobs
cache Generic cache helpers and collision-safe key builders
spaces DigitalOcean Spaces / S3-compatible storage with presigned URLs and key validation
metricserver Standalone Prometheus /metrics + /status server
validator Request validation via go-playground/validator with custom tags (regexp, …)
logutil zerolog level helpers
testutil Testcontainers helpers (PostgreSQL, Valkey) and Echo test contexts
util Date parsing and date-range validation helpers

πŸš€ Quick Start

A minimal service wired through the runner (see examples/minimal-api for the full program):

package main

import (
	"net/http"
	"time"

	"github.com/andyle182810/gframework/httpserver"
	"github.com/andyle182810/gframework/runner"
	"github.com/labstack/echo/v5"
)

func main() {
	server := httpserver.New(&httpserver.Config{
		Host:        "0.0.0.0",
		Port:        8080,
		BodyLimit:   "10M",
		GracePeriod: 10 * time.Second,
	})

	server.Root.GET("/health", func(c *echo.Context) error {
		return c.JSON(http.StatusOK, map[string]string{"status": "ok"})
	})

	// Blocks until SIGINT/SIGTERM or a service failure; exits non-zero on error.
	runner.New(
		runner.WithCoreService(server),
	).Run()
}

Services implement the runner.Service interface (Start(ctx) error, Stop() error, Name() string). Register databases, caches, and queues with WithInfrastructureService β€” they start first and stop last; register HTTP servers and subscribers with WithCoreService. If you need to manage signals or exit codes yourself (or drive the runner from a test), use RunContext(ctx) error instead of Run().

πŸ” Security configuration

The framework applies secure defaults, but several knobs are deployment-specific β€” review these before going to production:

JWT validation (middleware.JWTWithConfig): algorithm pinning is on by default (asymmetric algorithms only β€” HS* is rejected). Set Issuer and Audiences so tokens minted by other realms or for other services are rejected:

kf, _ := jwks.New(ctx, []string{"https://auth.example.com/realms/my-realm/protocol/openid-connect/certs"})

config := middleware.DefaultJWTConfig()
config.Keyfunc = kf
config.Issuer = "https://auth.example.com/realms/my-realm"
config.Audiences = []string{"my-service"}

e.Use(middleware.JWTWithConfig(config))

HTTP server timeouts (httpserver, metricserver): when unset, ReadHeaderTimeout 10s, ReadTimeout 30s, WriteTimeout 30s, IdleTimeout 120s. Override explicitly for streaming or long-polling endpoints.

CORS: EnableCors with an empty AllowOrigins allows every origin (and logs a warning). Always set AllowOrigins in production.

Internal service-to-service auth: protect internal endpoints with middleware.InternalAuth(kf, allowedClients); on the calling side, use httpclient with WithInternalAuthHeader() (the internal header is not sent by default β€” see Breaking changes below).

Error responses: never enable ErrorHandlerConfig.IncludeInternalErrors in production β€” it exposes internal error strings to clients.

Metrics: metricserver has no authentication. Bind it to an internal interface and keep it off the public network.

Request logs: values of sensitive query parameters (token, code, api_key, password, …) are automatically redacted.

Dependency scanning: CI runs govulncheck. Known remaining findings are confined to github.com/docker/docker via testcontainers (test-only dependency, no fixed release at the time of writing).

πŸ§ͺ Testing

The framework ships testcontainers helpers for integration tests (Docker required):

func TestWithPostgres(t *testing.T) {
	container := testutil.SetupPostgresContainer(t)

	db, err := postgres.New(&postgres.Config{URL: container.ConnectionString()})
	require.NoError(t, err)
	// Run tests...
}

Run everything:

make test       # go test ./... (no cache)
make lint       # go vet + golangci-lint v2 (fmt + run)

πŸ’‘ Examples

Example Shows
examples/minimal-api Smallest possible service: httpserver + runner + graceful shutdown
examples/jwt-auth JWKS + JWT middleware with issuer/audience pinning, realm roles, internal service auth
examples/messaging-worker Redis Streams pub/sub with retries + DLQ, periodic worker pool, distributed locks
examples/demo-api Full showcase: PostgreSQL, migrations, Swagger, Docker Compose

πŸ› οΈ Error handling conventions

  • Sentinel errors are package-level variables with the Err prefix (e.g. ErrConfigNil)
  • Errors are wrapped with fmt.Errorf("...: %w", err) for errors.Is/errors.As
  • HTTP errors use echo.HTTPError and are rendered by middleware.ErrorHandler

πŸ“š Key dependencies

πŸ“¬ Support

For bugs, questions, or feature requests, open an issue: πŸ‘‰ https://github.com/andyle182810/gframework/issues

πŸ“„ License

gframework is licensed under the MIT License. See LICENSE for details.

Directories ΒΆ

Path Synopsis
Package authtoken provides Keycloak service-account token management with automatic caching and refresh.
Package authtoken provides Keycloak service-account token management with automatic caching and refresh.
Package cache provides a generic, type-safe caching layer using Redis.
Package cache provides a generic, type-safe caching layer using Redis.
Package distlock provides Redis-backed distributed locking with two usage modes: fail-hard and fail-silent.
Package distlock provides Redis-backed distributed locking with two usage modes: fail-hard and fail-silent.
Package httpclient provides a generic, type-safe HTTP client for JSON REST APIs.
Package httpclient provides a generic, type-safe HTTP client for JSON REST APIs.
Package httpserver provides an opinionated HTTP server wrapper around Echo v5 with integrated middleware.
Package httpserver provides an opinionated HTTP server wrapper around Echo v5 with integrated middleware.
Package jwks provides a production-ready JWKS (JSON Web Key Set) key function for validating JWTs.
Package jwks provides a production-ready JWKS (JSON Web Key Set) key function for validating JWTs.
Package keycloak provides a Keycloak integration with two complementary clients:
Package keycloak provides a Keycloak integration with two complementary clients:
Package logutil provides log-level string parsing for zerolog and PostgreSQL query tracing.
Package logutil provides log-level string parsing for zerolog and PostgreSQL query tracing.
Package metricserver provides a dedicated HTTP server for operational endpoints: a /status health-check and a /metrics Prometheus scrape endpoint.
Package metricserver provides a dedicated HTTP server for operational endpoints: a /status health-check and a /metrics Prometheus scrape endpoint.
Package middleware provides reusable Echo v5 middleware and context value accessors for common patterns.
Package middleware provides reusable Echo v5 middleware and context value accessors for common patterns.
Package postgres provides a PostgreSQL connection pool factory with built-in support for decimal types, query tracing via zerolog, and configurable session-level timeouts.
Package postgres provides a PostgreSQL connection pool factory with built-in support for decimal types, query tracing via zerolog, and configurable session-level timeouts.
Package redispub provides a Redis Stream publisher using Watermill message bus.
Package redispub provides a Redis Stream publisher using Watermill message bus.
Package redissub provides a Redis Stream subscriber with automatic retry, timeout, and lifecycle management.
Package redissub provides a Redis Stream subscriber with automatic retry, timeout, and lifecycle management.
Package runner provides an application lifecycle manager for coordinated startup and graceful shutdown.
Package runner provides an application lifecycle manager for coordinated startup and graceful shutdown.
Package spaces provides an S3-compatible object storage client for DigitalOcean Spaces (or any S3-compatible endpoint) with presigned upload/download URLs, metadata lookup, ranged reads, and deletion.
Package spaces provides an S3-compatible object storage client for DigitalOcean Spaces (or any S3-compatible endpoint) with presigned upload/download URLs, metadata lookup, ranged reads, and deletion.
Package taskqueue provides a Redis-backed distributed task queue with at-least-once delivery semantics.
Package taskqueue provides a Redis-backed distributed task queue with at-least-once delivery semantics.
Package testutil provides integration-test helpers including Docker container setup, random data generation, context factories, and database utilities for testing gframework applications.
Package testutil provides integration-test helpers including Docker container setup, random data generation, context factories, and database utilities for testing gframework applications.
Package util provides small shared helpers: date parsing and date-range validation.
Package util provides small shared helpers: date parsing and date-range validation.
Package validator provides request validation for REST APIs using go-playground/validator with support for decimal types and JSON-based field naming.
Package validator provides request validation for REST APIs using go-playground/validator with support for decimal types and JSON-based field naming.
Package valkey provides a Valkey/Redis client wrapper with health checking and lifecycle management.
Package valkey provides a Valkey/Redis client wrapper with health checking and lifecycle management.
Package workerpool provides a generic, tick-driven worker pool that repeatedly invokes an Executor on a fixed interval.
Package workerpool provides a generic, tick-driven worker pool that repeatedly invokes an Executor on a fixed interval.

Jump to

Keyboard shortcuts

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