gocore

package module
v0.5.7 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2026 License: MIT Imports: 8 Imported by: 0

README

gocore

Engineering-first HTTP backend library for Go. Built for performance, security, and developer productivity at Oris Labs.

Go Version Go Report Card Coverage Status Security Policy


Why gocore?

In a world of "magic" frameworks, gocore takes a different approach. It provides a structured, production-ready foundation for Go services without hiding the standard library.

Feature net/http Gin / Echo gocore
Complexity Low High (Magic) Medium (Transparent)
Router Basic (pre-1.22) High-speed Radix High-speed Trie
Security Manual Middleware-based Hardened Defaults
Boilerplate High Low Low (Modular)
Standard Lib 100% Replaces Context 100% Compatible

gocore is designed for engineering teams who need to move fast but refuse to compromise on visibility, reliability, or security.


Engineering Evidence

Security Design & Threat Model

gocore is engineered with a multi-layered security approach:

  1. Attack Surface Reduction: Only 4 external dependencies (jwt, x/time, prometheus, redis). No bloated dependency trees.
  2. Hardened Defaults:
    • HSTS: Enforces HTTPS for 1 year by default.
    • CSP: Restrictive default-src 'self' policy.
    • Slowloris Protection: ReadHeaderTimeout set to 10s by default.
    • mTLS: Native support for client certificate verification.
  3. Threat Model Mitigation:
    • Injection: Path parameters are strictly parsed via Trie nodes.
    • Brute Force: Pluggable memory or Redis-backed token-bucket rate limiter per IP/Client.
    • Token Hijacking: JWT multi-source extraction (Header/Cookie) with TTL enforcement.
    • Metrics Cardinality: Prometheus metrics are protected against memory-exhaustion by tracking the underlying router pattern (e.g., /users/:id) instead of raw request URLs.
Architecture & Tradeoffs

The gocore architecture is strictly acyclic (config -> auth -> middleware -> router -> server -> core).

Tradeoff: Trie vs. Radix Router We chose a Trie-based router over a Radix tree. While Radix trees can be slightly faster for massive routing tables, the Trie implementation provides O(depth) matching and significantly clearer code for debugging complex REST patterns with wildcards and path parameters.

Benchmarks (O(depth) Performance)

Preliminary routing benchmarks indicate sub-microsecond matching latency for deep trees:

BenchmarkRouter/Static-4         232.3 ns/op          64 B/op          2 allocs/op
BenchmarkRouter/Param-4          440.7 ns/op         400 B/op          3 allocs/op
BenchmarkRouter/Wildcard-4       621.9 ns/op         544 B/op          5 allocs/op

Production Ready

Simplified Setup
app := gocore.New() // Starts with safe, hardened defaults
app.UseDefaults()    // RequestID, Recovery, Logger, Security, CORS, RateLimit

api := app.Group("/api/v1")
api.GET("/health", builtin.HealthCheck()).Public()

if err := app.Run(); err != nil {
    app.Logger().Fatal("server failed", "error", err)
}
Strategic Roadmap (v0.x)
  • v0.2.0: Prometheus metrics exporter integration.
  • v0.3.0: Distributed rate limiting (Redis provider).
  • v0.4.0: Automatic OpenAPI (Swagger) documentation generation.
  • v0.5.0: Websocket support.
  • v0.5.1: Updated to Go 1.25.0 and updated dependencies.
  • v0.5.2: WebSocket configuration and expansion.
  • v0.6.0: TBD.
  • v1.0.0: Stable API release.

Resources


© 2026 Oris Labs. Built by engineers, for engineers.

Documentation

Overview

Package gocore is a highly secure, optimized, and configurable HTTP backend library for Go applications.

Overview

gocore is designed to be installed as a dependency in a project and used as a full-featured HTTP backend foundation. It handles:

  • Routing — trie-based URL matching with path parameters and wildcards.
  • Middleware — composable, ordered middleware chains.
  • Security — JWT authentication, security headers, CORS, rate limiting.
  • Observability — structured access logging, panic recovery.
  • Lifecycle — graceful shutdown on SIGINT / SIGTERM.

All subsystems are individually configurable via the config package and can be replaced or extended independently.

Quick start

package main

import (
    "os"
    "github.com/orislabsdev/gocore"
    "github.com/orislabsdev/gocore/config"
    "github.com/orislabsdev/gocore/handler"
    "github.com/orislabsdev/gocore/middleware"
)

func main() {
    cfg := config.Default()
    cfg.Server.Port = 8080
    cfg.JWT.Secret = os.Getenv("JWT_SECRET")

    app := gocore.NewWithConfig(cfg)

    // Global middleware (applied to every request)
    app.Use(
        middleware.RequestID(),
        middleware.DefaultRecovery(app.Logger()),
        middleware.DefaultLogger(app.Logger()),
        middleware.Security(cfg.Security),
        middleware.CORS(cfg.CORS),
        middleware.RateLimit(cfg.RateLimit, app.Done()),
    )

    // Public route — no JWT required
    app.GET("/health", healthHandler).Public()

    // Private route group — JWT required
    api := app.Group("/api/v1")
    api.Use(middleware.Auth(middleware.AuthConfig{Manager: app.JWTManager()}))
    api.GET("/profile", getProfile)

    app.Run()
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Core

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

Core is the main application object. It wires together configuration, routing, middleware, authentication, and the HTTP server.

Create one Core per application (it is not designed to be shared across multiple HTTP listeners).

func New

func New() *Core

New creates a Core with production-safe defaults. Call NewWithConfig to override specific settings.

func NewWithConfig

func NewWithConfig(cfg *config.Config) *Core

NewWithConfig creates a Core with the provided configuration. Panics if the JWT secret is configured but invalid.

func (*Core) Config

func (c *Core) Config() *config.Config

Config returns the root configuration. Useful when building custom middleware that reads from the same configuration source.

func (*Core) DELETE

func (c *Core) DELETE(path string, h handler.HandlerFunc) *router.Route

DELETE registers a DELETE handler.

func (*Core) Done

func (c *Core) Done() <-chan struct{}

Done returns a channel that is closed when the server begins shutting down. Pass this to middleware that run background goroutines (e.g., RateLimit).

func (*Core) GET

func (c *Core) GET(path string, h handler.HandlerFunc) *router.Route

GET registers a GET handler. Returns a *Route for fluent chaining (.Public(), .Name(), .Use()).

func (*Core) Group

func (c *Core) Group(prefix string) *router.Group

Group creates a route group with a shared path prefix. Use groups to scope middleware (e.g., JWT auth) to a sub-tree of routes.

api := app.Group("/api/v1")
api.Use(middleware.Auth(...))
api.GET("/users", listUsers)

func (*Core) HEAD

func (c *Core) HEAD(path string, h handler.HandlerFunc) *router.Route

HEAD registers a HEAD handler.

func (*Core) Handler

func (c *Core) Handler() http.Handler

Handler returns the Core's router as an http.Handler. Use this when embedding gocore into an existing net/http setup instead of calling Run.

http.ListenAndServe(":8080", app.Handler())

func (*Core) JWTManager

func (c *Core) JWTManager() *auth.Manager

JWTManager returns the auth.Manager for issuing and validating tokens. Returns nil if no JWT secret was configured.

func (*Core) Logger

func (c *Core) Logger() *logger.Logger

Logger returns the application logger. Use it in your own handlers and middleware for consistent structured output.

func (*Core) OPTIONS

func (c *Core) OPTIONS(path string, h handler.HandlerFunc) *router.Route

OPTIONS registers an OPTIONS handler.

func (*Core) PATCH

func (c *Core) PATCH(path string, h handler.HandlerFunc) *router.Route

PATCH registers a PATCH handler.

func (*Core) POST

func (c *Core) POST(path string, h handler.HandlerFunc) *router.Route

POST registers a POST handler.

func (*Core) PUT

func (c *Core) PUT(path string, h handler.HandlerFunc) *router.Route

PUT registers a PUT handler.

func (*Core) Router

func (c *Core) Router() *router.Router

Router returns the underlying *router.Router for advanced use cases.

func (*Core) Run

func (c *Core) Run() error

Run starts the HTTP server and blocks until the server receives a shutdown signal (SIGINT/SIGTERM) or encounters an unrecoverable error.

Run handles the full lifecycle:

  1. Starts the HTTP (or HTTPS) listener.
  2. Waits for an OS signal.
  3. Closes the done channel (stopping background goroutines like RateLimit).
  4. Drains active connections (up to ShutdownTimeout).
  5. Returns nil on clean exit, or the error that caused the failure.

func (*Core) Use

func (c *Core) Use(mw ...handler.MiddlewareFunc)

Use appends one or more global middleware to the application. Global middleware runs on every request before route-specific middleware. Must be called before Run.

func (*Core) UseDefaults

func (c *Core) UseDefaults()

UseDefaults installs the recommended set of global middleware in the standard order:

  1. RequestID — ensure every request has a unique ID.
  2. Recovery — catch panics and return 500.
  3. Logger — emit a structured access-log entry.
  4. Security — set HTTP security headers.
  5. CORS — enforce the CORS policy.
  6. RateLimit — enforce per-client rate limits.

Authentication (JWT) is intentionally omitted from the default set because it should be applied to specific route groups, not globally. Register it on a group via group.Use(middleware.Auth(...)).

Call UseDefaults before registering routes and before calling Run.

Directories

Path Synopsis
Package auth provides JSON Web Token (JWT) generation and validation utilities used by the gocore authentication middleware.
Package auth provides JSON Web Token (JWT) generation and validation utilities used by the gocore authentication middleware.
Package builtin provides ready-made handlers for common operational endpoints that every backend service should expose.
Package builtin provides ready-made handlers for common operational endpoints that every backend service should expose.
Package config provides all configuration structures for the gocore library.
Package config provides all configuration structures for the gocore library.
Command example demonstrates how to use the gocore library as a backend foundation.
Command example demonstrates how to use the gocore library as a backend foundation.
Package handler provides the core types that route handlers interact with.
Package handler provides the core types that route handlers interact with.
Package logger provides a lightweight, structured, leveled logger for the gocore library and for application code.
Package logger provides a lightweight, structured, leveled logger for the gocore library and for application code.
Package middleware provides production-ready HTTP middleware for the gocore library.
Package middleware provides production-ready HTTP middleware for the gocore library.
Package router provides a high-performance, trie-based HTTP router for the gocore library.
Package router provides a high-performance, trie-based HTTP router for the gocore library.
Package server provides the HTTP/HTTPS server for the gocore library.
Package server provides the HTTP/HTTPS server for the gocore library.
Package validate provides lightweight, zero-dependency request validation utilities for the gocore library.
Package validate provides lightweight, zero-dependency request validation utilities for the gocore library.

Jump to

Keyboard shortcuts

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