requestCore

package module
v0.29.1 Latest Latest
Warning

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

Go to latest
Published: Sep 12, 2026 License: MIT Imports: 5 Imported by: 0

README

requestCore

Framework-agnostic Go request lifecycle — one handler API across Gin, Fiber, and net/http

Go Reference Release License Go Version CI golangci-lint Ask DeepWiki

Quick Start · Examples · Why · Features · Docs · Contributing · Roadmap


requestCore is a Go library for handling RESTful requests with a framework-agnostic core and adapters for Gin, Fiber, and net/http. It provides a unified request/context layer, query execution abstractions, response handling, logging, tracing, and testing utilities.

It is designed to reduce boilerplate around request processing while keeping the implementation composable, interface-driven, and portable across web frameworks.


Why requestCore?

The problem

Every backend service repeats the same cross-cutting work on every request: parse the input consistently, log and trace the call, detect duplicates, run the query, and return a uniform error response. Most teams hand-write this once per framework — and pay for it again when they adopt or migrate to a second one. The result is boilerplate that is locked to Gin, Fiber, or chi and can't move.

What requestCore gives you
  • One request API across Gin, Fiber, and net/http via webFramework.RequestParser
  • Composable handler pipeline — parse, validate, persist, execute, respond (handlers/baseHandler.go)
  • Database abstraction — Oracle, PostgreSQL, MySQL, SQLite, MockDB (libQuery/)
  • Observability built in — OpenTelemetry, slog, Splunk adapters (libTracing/, libLogger/)
  • Incremental adoption — use only the adapter/parser layer, or the full request lifecycle
When to use it
  • Teams on multiple HTTP frameworks (or migrating between them)
  • Services needing request audit/persistence and duplicate checking
  • Projects using sqlc + database/sql or GORM with shared query/error handling
  • Platforms standardizing logging and tracing without coupling business logic to Gin/Fiber
When not to use it
  • A minimal API where stdlib or a single framework with no shared infra is enough
  • Greenfield apps that won't need request persistence, multi-DB, or cross-framework portability
Compared to alternatives
Approach Strength requestCore adds
Raw Gin / Fiber / chi Simple, fast Unified parsing, lifecycle, DB, observability across frameworks
Middleware-only stack Lightweight Request persistence, duplicate detection, query runner, handler orchestration
Rolling your own Full control Reusable, tested abstractions already in this repo

See it in action

Runnable examples: examples/

Each example exposes the same three routes (/health, /users/{id}, /echo) so you can see the same handler code run unchanged across frameworks.

Demo asset (TODO): an architecture diagram or asciinema cast showing the same handler running under chi, Gin, and Fiber would belong here. Not yet produced — contributions welcome (see Contributing).


Quick start

Pick a runnable example:

go run ./examples/chi-hello
curl http://localhost:8080/users/42

For the full request lifecycle (DB, persistence, handlers), see examples/README.md and the handlers package.

Installation
go get github.com/hmmftg/requestCore

Then import the package in your project:

import "github.com/hmmftg/requestCore"

Features

  • Framework adapters

    • Gin
    • Fiber
    • net/http
    • testing support
  • Unified request context

    • normalized access to framework context
    • request metadata extraction
    • trace propagation
    • user identity handling
  • Query and DB abstraction

    • multi-database support
    • query runner abstraction
    • mock database mode for tests
  • Request lifecycle helpers

    • request initialization
    • duplicate request detection
    • request insert/update flows
    • context-aware request operations
  • Structured logging

    • slog-based logging support
    • framework-aware logger integrations
    • Splunk-oriented logging support
  • OpenTelemetry support

    • trace extraction and propagation
    • request context instrumentation
    • observability-friendly design
  • Testing utilities

    • fake/mock infrastructure
    • testing-aware context initialization
    • mock DB mode
  • Additional utilities

    • validation helpers
    • response helpers
    • error handling
    • crypto/security helpers
    • HTTP API calling utilities
    • Swagger-related support

Architecture overview

The repository is centered around a thin root façade and multiple focused subpackages, organized around small interfaces and adapter packages rather than a single large runtime framework.

Root façade
  • requestCore.go
    • exposes the main RequestCoreModel
    • provides access to:
      • DB/query runner
      • ORM interface
      • request tools
      • response handler
      • parameter interface
Core layers
  • libContext

    • framework-aware context initialization
    • tracing extraction
    • user and framework metadata handling
  • libRequest

    • request lifecycle and persistence operations
    • initialization paths with and without logging
    • duplicate detection
    • context-aware updates
  • libQuery

    • query runner abstraction
    • DB mode handling
    • execution helpers
    • ORM-oriented query support
  • response

    • response handling
    • error response modeling
    • sanitization and web handler support
  • libParams

    • parameter modeling and loading
    • networking, logging, DB, and security parameters
Framework adapters
  • libGin
  • libFiber
  • libNetHttp
  • webFramework
Supporting packages
  • libLogger
  • libTracing
  • libError
  • libValidate
  • libCallApi
  • libCrypto
  • handlers
  • swagger
  • testingtools
Package reference
Package Responsibility
requestCore.go Root façade exposing the main interfaces
libContext Detects and normalizes framework context (Gin, Fiber, net/http, testing); integrates tracing metadata and user identity extraction
libRequest Request operations: initialization, duplicate checking, request insertion, updates with context, no-log initialization path
libQuery Database/query layer with multiple DB modes: Oracle, PostgreSQL, SQLite, MySQL, Mock DB
response Response generation and error handling utilities
libLogger Logging utilities, including slog and Splunk-oriented integrations
libTracing OpenTelemetry-related tracing and instrumentation helpers
libValidate Input validation helpers
libCallApi Utilities for calling external APIs and handling auth/multi-call scenarios
libCrypto Cryptographic and security primitives
handlers Reusable handler implementations for request, query, DML, pagination, recovery, and API call flows
testingtools Test helpers, mocks, and simulation utilities
libCallApi remote API auth

Remote APIs can authenticate with OAuth2 (client_credentials, refresh_token, optional password grant) or fall back to BasicAuth when grant-type is not configured.

Example param.yaml:

remoteApis:
  partner-api:
    domain: https://api.partner.com
    name: partner-api
    auth:
      grant-type: client_credentials
      auth-uri: https://auth.partner.com/oauth/token
      client-id: partner-client

Secure values (existing pattern):

  • remote-api#partner-api#client-secret
  • remote-api#partner-api#client-id
  • remote-api#partner-api#auth-uri (alias: auth-url)

Supported web frameworks

requestCore currently supports:


Requirements

  • Go 1.27+
  • A supported SQL database driver, depending on your chosen DB mode
  • Optional:
    • OpenTelemetry
    • structured logging backend
    • ORM integration

Release Lines

This repository contains two independent Go modules with separate release streams:

Module Import path Tags Status
Root (v1) github.com/hmmftg/requestCore v0.x.y, v1.x.y Stable (v1.0 line)
v2 github.com/hmmftg/requestCore/v2 v2/v2.x.y Alpha prerelease

Canonical setup: chi + net/http + sqlc + pgx/stdlib

For low-risk adoption, use sqlc in database/sql mode and connect PostgreSQL with pgx stdlib.

1) sqlc configuration
version: "2"
sql:
  - schema: "db/schema.sql"
    queries: "db/query.sql"
    engine: "postgresql"
    gen:
      go:
        package: "db"
        out: "internal/db"
        sql_package: "database/sql"
2) Open DB with pgx stdlib
import (
	"database/sql"

	_ "github.com/jackc/pgx/v5/stdlib"
)

db, err := sql.Open("pgx", "postgres://user:pass@localhost:5432/appdb?sslmode=disable")
if err != nil {
	panic(err)
}
defer db.Close()
3) Use chi route params with requestCore net/http parser
router := chi.NewRouter()
router.Get("/users/{id}", func(w http.ResponseWriter, r *http.Request) {
	parser := libChi.InitParser(r, w)
	id := parser.GetUrlParam("id")
	_ = parser.SendJSONRespBody(http.StatusOK, map[string]string{"id": id})
})

This path keeps compatibility with the current database/sql-oriented query layer and enables incremental adoption.


Testing

The repository includes a strong testing story:

  • framework-aware testing support
  • mock DB mode
  • fake API helpers
  • package-level unit tests
  • testing context support

This allows request handling, query execution, and framework adapters to be tested independently.


Optional advanced path: pgx-native sqlc mode

If you need sqlc generated code for pgx/v5 native interfaces (instead of database/sql), treat it as a separate compatibility track:

  • keep current QueryRunnerInterface (database/sql) for backward compatibility
  • add a parallel pgx-native runner contract and adapter implementation
  • maintain parity tests for both backends:
    • query behavior and error mapping
    • DML behavior
    • tracing/logging hooks

Suggested parity matrix:

Capability database/sql backend pgx-native backend
Single-row query mapping required required
Multi-row query mapping required required
DML affected rows handling required required
Duplicate / no-data error mapping required required
Request-scoped tracing attributes required required
Existing handlers compatibility required required

This minimizes risk for existing users while allowing pgx-native optimization where needed.


Observability

requestCore is observability-friendly and includes support for:

  • trace context extraction
  • OpenTelemetry integration
  • framework-aware logging
  • structured logs via slog
  • framework-specific logging adapters

This makes it suitable for services that need request-level visibility without hard-coding observability into business logic.


Database support

The query layer supports multiple DB modes, including:

  • Oracle
  • PostgreSQL
  • SQLite
  • MySQL
  • Mock DB

This makes the library suitable for heterogeneous environments and for testing without a real database.


Design principles

requestCore follows these principles:

  • composition over inheritance
  • framework portability
  • interface-driven design
  • explicit abstractions
  • observability by default
  • testability first

Repository structure

requestCore/
├── requestCore.go
├── examples/
├── libContext/
├── libRequest/
├── libQuery/
├── libParams/
├── response/
├── libLogger/
├── libTracing/
├── libValidate/
├── libCallApi/
├── libCrypto/
├── handlers/
├── swagger/
├── testingtools/
├── libGin/
├── libFiber/
├── libNetHttp/
└── webFramework/

Documentation

Guides live in docs/:


Articles


v2: Generics-First Module

The v2/ directory contains a separate Go module (github.com/hmmftg/requestCore/v2) that builds on the root module with a generics-first API. It requires Go 1.27+ for generic methods.

What v2 adds
  • Generic typed endpointshandlers.Endpoint[Req, Resp] with typed lifecycle hooks (WithInitializer, WithFinalizer, WithPersistence)
  • Generic resourcesresources.ResourceBuilder[ID] + resources.Resource[ID cmp.Ordered] with 7 CRUD operations (TypedResource with 14 type params is an advanced alternative, overkill for simple CRUD)
  • Typed session accesssession.GetTyped[T] / session.SetTyped[T] (no runtime type assertions)
  • Generic response helpersresponse.Handler.OKTyped[Resp] / OKWithStatusTyped[Resp]
  • Framework-agnostic routing — Gin, Fiber, chi, net/http via adapters
  • Pluggable renderers — JSON, XML, text, CSV
  • Background workers — bounded pool with retry, tracing, and mandatory webFramework.AddLog observability
  • Scheduler — periodic background tasks
  • CLIrequestcore code generator for handlers, resources, middleware, projects
Quick example
package main

import (
    "context"
    "log"
    "os/signal"
    "syscall"

    "github.com/hmmftg/requestCore/v2/app"
    "github.com/hmmftg/requestCore/v2/handlers"
    "github.com/hmmftg/requestCore/v2/renderers"
    "github.com/hmmftg/requestCore/v2/request"
)

type HealthReq struct{}

type HealthResp struct {
    Status string `json:"status"`
}

func main() {
    application, err := app.Bootstrap(app.Config{
        Framework: app.FrameworkChi,
        Renderer:  renderers.JSONRenderer{},
    })
    if err != nil {
        log.Fatal(err)
    }
    defer application.Close()

    // Register a typed GET endpoint using the canonical handler signature.
    err = handlers.GetEndpoint[HealthReq, HealthResp](
        application.Router, application.Executor, "/health",
        func(ctx *request.Context, req HealthReq) (HealthResp, error) {
            return HealthResp{Status: "healthy"}, nil
        },
    )
    if err != nil {
        log.Fatal(err)
    }

    ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
    defer stop()

    if err := application.StartWithContext(ctx, ":8080"); err != nil {
        log.Fatal(err)
    }
}
Documentation

Roadmap

This is a living document; items move as priorities shift.

  • v2 stabilization — take the v2 generics-first kernel from alpha to a stable tag
  • More framework adapters — Echo, standard library router, and others by community request
  • Documentation site — consolidate the guides under docs/ into a rendered site (mkdocs or GitHub Pages)
  • Demo assets — architecture diagram and an asciinema cast of the cross-framework examples
  • Benchmark suite — publish comparable cross-framework overhead numbers (none exist yet)
  • More database integrations — expand the libQuery DB mode matrix

See CHANGELOG.md for release history.


Contributing

Contributions are welcome — see CONTRIBUTING.md for setup, testing, lint, and commit conventions.

Suggested areas for contribution:

  • framework adapters
  • documentation
  • observability enhancements
  • request lifecycle helpers
  • database integrations
  • tests and examples

Community

Questions, ideas, or use cases? Open a GitHub Discussion — that's the place for Q&A and announcements. Bugs and feature requests go in Issues.

Note: Discussions must be enabled in repository Settings → General → Features. See CONTRIBUTING.md for the manual setup checklist.


Citation

If requestCore is useful in your work, please cite it:

@software{malek_mohammadi_2026_requestcore,
  author       = {Hamid Malek Mohammadi},
  title        = {requestCore: Framework-agnostic Go request lifecycle},
  year         = {2026},
  publisher    = {GitHub},
  url          = {https://github.com/hmmftg/requestCore},
  license      = {MIT}
}

See also CITATION.cff (renders a "Cite this repository" button on GitHub).


Security

Reporting a vulnerability? Please see SECURITY.md. Do not open a public issue for security reports.


License

MIT — Copyright (c) 2026 Hamid Malek Mohammadi.

Documentation

Overview

Package requestCore provides the core request processing pipeline framework.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type RequestCoreInterface

type RequestCoreInterface interface {
	GetDB() libQuery.QueryRunnerInterface
	ORM() liborm.OrmInterface
	RequestTools() libRequest.RequestInterface
	Responder() response.ResponseHandler
	Params() libParams.ParamInterface
}

RequestCoreInterface defines the accessor methods for the core request processing model.

type RequestCoreModel

type RequestCoreModel struct {
	RequestInterface libRequest.RequestInterface
	QueryInterface   libQuery.QueryRunnerInterface
	OrmInterface     liborm.OrmInterface
	RespHandler      response.ResponseHandler
	ParamMap         libParams.ParamInterface
}

RequestCoreModel is the central model holding query, ORM, request, response, and parameter interfaces.

func (RequestCoreModel) GetDB

GetDB returns the query runner interface for database access.

func (RequestCoreModel) ORM added in v0.16.4

ORM returns the ORM interface for Gorm-based database access.

func (RequestCoreModel) Params added in v0.4.15

Params returns the application parameter interface.

func (RequestCoreModel) RequestTools

func (m RequestCoreModel) RequestTools() libRequest.RequestInterface

RequestTools returns the request interface for request lifecycle management.

func (RequestCoreModel) Responder

Responder returns the response handler for formatting HTTP responses.

Directories

Path Synopsis
Package conformance provides shared data-only HTTP conformance vectors for cross-version testing of requestCore v1 and v2.
Package conformance provides shared data-only HTTP conformance vectors for cross-version testing of requestCore v1 and v2.
examples
chi-hello command
Package main implements a chi-based HTTP server example using requestCore.
Package main implements a chi-based HTTP server example using requestCore.
fiber-hello command
Package main implements a Fiber-based HTTP server example using requestCore.
Package main implements a Fiber-based HTTP server example using requestCore.
gin-hello command
Package main implements a Gin-based HTTP server example using requestCore.
Package main implements a Gin-based HTTP server example using requestCore.
Package handlers provides request handler primitives for requestCore applications.
Package handlers provides request handler primitives for requestCore applications.
Package httpsemantics provides stdlib-only helpers for HTTP standards including OAuth token-response cache headers, RFC 6750 Bearer challenges, RFC 9110 conditional requests, RFC 8288 Link headers, and RFC 9110 Retry-After parsing/formatting.
Package httpsemantics provides stdlib-only helpers for HTTP standards including OAuth token-response cache headers, RFC 6750 Bearer challenges, RFC 9110 conditional requests, RFC 8288 Link headers, and RFC 9110 Retry-After parsing/formatting.
Package idempotency provides reusable contracts for HTTP idempotency key handling, request fingerprinting, and replay-safe response capture.
Package idempotency provides reusable contracts for HTTP idempotency key handling, request fingerprinting, and replay-safe response capture.
Package initiator provides application initialization utilities for Gin-based services.
Package initiator provides application initialization utilities for Gin-based services.
metrics
Package metrics provides Prometheus metrics collection for requestCore applications.
Package metrics provides Prometheus metrics collection for requestCore applications.
Package libCallApi provides HTTP client utilities for consuming remote REST APIs.
Package libCallApi provides HTTP client utilities for consuming remote REST APIs.
Package libChi provides a Chi web framework adapter for requestCore.
Package libChi provides a Chi web framework adapter for requestCore.
Package libContext provides context initialization utilities for requestCore handlers.
Package libContext provides context initialization utilities for requestCore handlers.
Package libCrypto provides cryptographic utility wrappers.
Package libCrypto provides cryptographic utility wrappers.
ssm
Package ssm provides cryptographic utilities for banking SSM operations.
Package ssm provides cryptographic utilities for banking SSM operations.
Package libDictionary provides dictionary/lookup utilities for requestCore.
Package libDictionary provides dictionary/lookup utilities for requestCore.
Package libError provides structured error handling with action and source tracking.
Package libError provides structured error handling with action and source tracking.
Package libFiber provides a Fiber web framework adapter for requestCore.
Package libFiber provides a Fiber web framework adapter for requestCore.
logger
Package logger provides Fiber middleware logging integration.
Package logger provides Fiber middleware logging integration.
Package libGin provides a Gin web framework adapter for requestCore.
Package libGin provides a Gin web framework adapter for requestCore.
initiator
Package gininitiator provides Gin engine initialization with middleware setup.
Package gininitiator provides Gin engine initialization with middleware setup.
logger
Package logger provides Gin middleware logging integration.
Package logger provides Gin middleware logging integration.
logger/ginsplunk
Package ginsplunk provides Gin Splunk logging middleware integration.
Package ginsplunk provides Gin Splunk logging middleware integration.
Package libLogger provides structured logging utilities for requestCore.
Package libLogger provides structured logging utilities for requestCore.
splunk
Package splunk provides Splunk HTTP event collector integration for requestCore logging.
Package splunk provides Splunk HTTP event collector integration for requestCore logging.
Package libNetHttp provides a net/http web framework adapter for requestCore.
Package libNetHttp provides a net/http web framework adapter for requestCore.
Package libParams provides application parameter configuration management.
Package libParams provides application parameter configuration management.
Package libQuery provides database query runner abstractions for requestCore.
Package libQuery provides database query runner abstractions for requestCore.
liborm
Package liborm provides ORM-based query execution using Gorm.
Package liborm provides ORM-based query execution using Gorm.
mockdb
Package mockdb provides mock database helpers for testing query runners.
Package mockdb provides mock database helpers for testing query runners.
notify command
Package main provides database notification/listen utilities for PostgreSQL.
Package main provides database notification/listen utilities for PostgreSQL.
Package libRequest provides request parsing and validation utilities.
Package libRequest provides request parsing and validation utilities.
Package libRetry provides retry policies with exponential backoff for function execution.
Package libRetry provides retry policies with exponential backoff for function execution.
Package libTracing provides OpenTelemetry tracing integration for requestCore.
Package libTracing provides OpenTelemetry tracing integration for requestCore.
Package libValidate provides request field validation with custom and system validators.
Package libValidate provides request field validation with custom and system validators.
Package libsql provides SQL query execution utilities with result scanning.
Package libsql provides SQL query execution utilities with result scanning.
Package response provides HTTP response and error handling for requestCore.
Package response provides HTTP response and error handling for requestCore.
Package status provides HTTP and application status code constants.
Package status provides HTTP and application status code constants.
Package swagger provides Swagger/OpenAPI documentation integration for Gin.
Package swagger provides Swagger/OpenAPI documentation integration for Gin.
Package testingtools provides test helpers and mock infrastructure for requestCore.
Package testingtools provides test helpers and mock infrastructure for requestCore.
Package webFramework provides the web framework abstraction layer for requestCore.
Package webFramework provides the web framework abstraction layer for requestCore.

Jump to

Keyboard shortcuts

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