middleware

package module
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Jul 21, 2026 License: AGPL-3.0 Imports: 15 Imported by: 2

README

ICAA Middleware

A Go HTTP middleware library for the International Combat Archery Alliance, providing reusable components for web applications including request logging, authentication context, Swagger UI hosting, and path prefix management.

Features

Core Middleware
  • Request Logging: Structured access logging with request IDs, latency tracking, and response metrics
  • Context Management: Request-scoped context for request IDs, loggers, and JWT tokens
  • Base Path Prefixes: URL path prefix modification for service routing
  • Middleware Composition: Utility for composing multiple middlewares
Swagger UI Integration
  • Embedded Swagger UI: Self-contained Swagger UI hosting with embedded assets
  • OpenAPI Specification Serving: Automatic serving of OpenAPI JSON specifications
  • Configurable Base Paths: Flexible path configuration for API documentation

Installation

go get github.com/International-Combat-Archery-Alliance/middleware

Usage

Basic Middleware Setup
package main

import (
    "log/slog"
    "net/http"
    
    "github.com/International-Combat-Archery-Alliance/middleware"
)

func main() {
    mux := http.NewServeMux()
    logger := slog.Default()
    
    // Add your routes
    mux.HandleFunc("/api/health", healthHandler)
    
    // Apply middlewares
    handler := middleware.UseMiddlewares(mux,
        middleware.AccessLogging(logger),
        middleware.BaseNamePrefix(logger, "/api/v1"),
    )
    
    http.ListenAndServe(":8080", handler)
}
Swagger UI Hosting
import (
    "github.com/getkin/kin-openapi/openapi3"
    "github.com/International-Combat-Archery-Alliance/middleware"
)

func setupSwagger(spec *openapi3.T) http.Handler {
    mux := http.NewServeMux()
    
    // Host Swagger UI at /docs/swagger-ui with spec at /docs/openapi.json
    swaggerMiddleware, err := middleware.HostSwaggerUI("/docs", spec)
    if err != nil {
        log.Fatal(err)
    }
    
    handler := middleware.UseMiddlewares(mux, swaggerMiddleware)
    return handler
}
Context Usage
func apiHandler(w http.ResponseWriter, r *http.Request) {
    // Get request-scoped logger
    if logger, ok := middleware.GetLoggerFromCtx(r.Context()); ok {
        logger.Info("Processing API request")
    }
    
    // Get request ID
    if reqID, ok := middleware.GetRequestIdFromCtx(r.Context()); ok {
        w.Header().Set("X-Request-ID", reqID.String())
    }
    
    // Get JWT token (if authentication middleware is used)
    if token, ok := middleware.GetJWTFromCtx(r.Context()); ok {
        // Use token for authorization
        _ = token
    }
}

Middleware Components

AccessLogging

Provides structured HTTP access logging with:

  • Request ID generation and tracking
  • Request/response size logging
  • Latency measurement
  • HTTP method, path, and status code logging
  • Integration with Go's slog structured logging
BaseNamePrefix

Modifies request URLs by prepending a base path, useful for:

  • API versioning (/api/v1)
  • Service routing in reverse proxy setups
  • Path-based service isolation
HostSwaggerUI

Serves Swagger UI documentation with:

  • Embedded Swagger UI assets (no external dependencies)
  • Automatic OpenAPI specification serving
  • Configurable base paths for documentation endpoints

Context Utilities

The library provides context management utilities for:

  • Request IDs: UUID-based request tracking across middleware chain
  • Structured Logging: Request-scoped loggers with automatic request ID correlation
  • JWT Tokens: Authentication token storage and retrieval (integrates with ICAA auth library)

Dependencies

  • github.com/International-Combat-Archery-Alliance/auth: Authentication and JWT handling
  • github.com/getkin/kin-openapi: OpenAPI specification parsing and validation
  • github.com/google/uuid: UUID generation for request tracking
  • Standard library packages for HTTP handling and logging

License

Licensed under the GNU Affero General Public License v3.0. See LICENSE for details.

Contributing

This library is part of the International Combat Archery Alliance's software infrastructure. Contributions should follow the project's coding standards and include appropriate tests.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CtxWithClientIP added in v0.5.0

func CtxWithClientIP(ctx context.Context, ip string) context.Context

func CtxWithJWT

func CtxWithJWT(ctx context.Context, jwt auth.AuthToken) context.Context

func CtxWithLogger

func CtxWithLogger(ctx context.Context, logger *slog.Logger) context.Context

func CtxWithRefreshTokenID added in v0.2.0

func CtxWithRefreshTokenID(ctx context.Context, tokenID string) context.Context

CtxWithRefreshTokenID stores a refresh token ID in the context

func CtxWithSpanID added in v0.3.0

func CtxWithSpanID(ctx context.Context, spanID string) context.Context

func CtxWithTraceID added in v0.3.0

func CtxWithTraceID(ctx context.Context, traceID string) context.Context

func GetClientIPFromCtx added in v0.5.0

func GetClientIPFromCtx(ctx context.Context) (string, bool)

func GetJWTFromCtx

func GetJWTFromCtx(ctx context.Context) (auth.AuthToken, bool)

func GetLoggerFromCtx

func GetLoggerFromCtx(ctx context.Context) (*slog.Logger, bool)

func GetRefreshTokenIDFromCtx added in v0.2.0

func GetRefreshTokenIDFromCtx(ctx context.Context) (string, bool)

GetRefreshTokenIDFromCtx retrieves a refresh token ID from the context

func GetSpanIDFromCtx added in v0.3.0

func GetSpanIDFromCtx(ctx context.Context) (string, bool)

func GetTraceIDFromCtx added in v0.3.0

func GetTraceIDFromCtx(ctx context.Context) (string, bool)

func OTELHandler added in v0.4.0

func OTELHandler(next http.Handler) http.Handler

OTELHandler wraps the provided handler with OpenTelemetry HTTP tracing. It uses a span name formatter of "METHOD PATH" (e.g. "GET /login/v1/sessions").

func UseMiddlewares

func UseMiddlewares(r *http.ServeMux, middlewares ...MiddlewareFunc) http.Handler

Types

type CorsConfig added in v0.2.0

type CorsConfig struct {
	LocalOrigins []string
	ProdOrigins  []string
	IsProduction bool
}

CorsConfig holds configuration for CORS middleware

func DefaultCorsConfig added in v0.2.0

func DefaultCorsConfig() CorsConfig

DefaultCorsConfig returns a default CORS configuration for ICAA services

type MiddlewareFunc

type MiddlewareFunc func(next http.Handler) http.Handler

func AccessLogging

func AccessLogging(baseLogger *slog.Logger) MiddlewareFunc

func BaseNamePrefix

func BaseNamePrefix(logger *slog.Logger, baseName string) MiddlewareFunc

func CorsMiddleware added in v0.2.0

func CorsMiddleware(config CorsConfig) MiddlewareFunc

CorsMiddleware creates a CORS middleware with the given configuration

func FlushTraces added in v0.4.0

func FlushTraces(flush func(context.Context) error, logger *slog.Logger, timeout time.Duration) MiddlewareFunc

FlushTraces returns a middleware that flushes trace spans after the request has been handled. The flush runs with the provided timeout. If flush is nil, the middleware is a no-op.

func HostSwaggerUI

func HostSwaggerUI(basePath string, spec *openapi3.T) (MiddlewareFunc, error)

Jump to

Keyboard shortcuts

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