middleware.go

Overview

The [middleware.go](/projects/291/69274) file provides HTTP middleware components for the API server built using the Gorilla Mux router. Middleware functions are wrappers around HTTP handlers that execute code before and/or after the main handler logic. This file primarily implements:

These middleware layers enhance observability, metrics collection, and correct request context handling needed throughout the API service.


Detailed Explanation of Components

Struct: statusWriter

type statusWriter struct {
	http.ResponseWriter
	status int
}

Functions related to statusWriter


Middleware Function: Logger

func Logger(prometheus *metrics.Prometheus) mux.MiddlewareFunc

Behavior:

Usage Example

router := mux.NewRouter()
prometheus := metrics.NewPrometheus()

router.Use(api.Logger(prometheus))

Middleware Function: Scheme

func Scheme(next http.Handler) http.Handler

Behavior:

Example Usage

router := mux.NewRouter()
router.Use(api.Scheme)

Important Implementation Details


Interaction with Other System Components


Visual Diagram

flowchart TD
    subgraph MiddlewareChain
        direction TB
        Request --> SchemeMiddleware[Scheme Middleware]
        SchemeMiddleware --> LoggerMiddleware[Logger Middleware]
        LoggerMiddleware --> Handler[Final HTTP Handler]
    end

    subgraph LoggerMiddlewareDetails
        LoggerMiddleware --> WrapResponseWriter[Wrap with statusWriter]
        WrapResponseWriter --> CallNextHandler
        CallNextHandler --> MeasureDuration
        MeasureDuration --> LogRequestAndMetrics
    end

    subgraph SchemeMiddlewareDetails
        SchemeMiddleware --> ExtractHeaders[Extract Scheme Headers]
        ExtractHeaders --> DetermineScheme[Determine URL Scheme]
        DetermineScheme --> SetRequestScheme[Set r.URL.Scheme]
    end

    style MiddlewareChain fill:#f9f,stroke:#333,stroke-width:1px
    style LoggerMiddlewareDetails fill:#bbf,stroke:#333,stroke-width:1px
    style SchemeMiddlewareDetails fill:#bbf,stroke:#333,stroke-width:1px

Summary

The [middleware.go](/projects/291/69274) file offers essential HTTP middleware for the API server to:

By integrating these middleware functions into the HTTP router, the application enhances reliability, debugging, and monitoring capabilities critical for production-grade APIs.