aichteeteapee

package module
v1.3.0 Latest Latest
Warning

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

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

README

aichteeteapee

Pronounced "HTTP". The name is the whole joke. Moving on.

A Go HTTP library that does everything you need and nothing you don't. Spin up a production-ready server with middleware, WebSocket hubs, file uploads, static serving, request proxying with caching, and OpenAPI validation — all with sane defaults and zero boilerplate.

Table of Contents

srv, _ := server.New()

router := &server.Router{
    GlobalMiddlewares: []middleware.Middleware{
        middleware.RequestID(),
        middleware.Logger(),
        middleware.Recovery(),
        middleware.SecurityHeaders(),
    },
    Groups: []server.GroupConfig{{
        Path: "/",
        Routes: []server.RouteConfig{{
            Method:  http.MethodGet,
            Path:    "/hello",
            Handler: func(w http.ResponseWriter, _ *http.Request) {
                aichteeteapee.WriteJSON(w, http.StatusOK, map[string]string{"msg": "hi"})
            },
        }},
    }},
}

srv.Start(ctx, router)

Request IDs, structured logging, panic recovery, security headers, graceful shutdown, TLS support. You pick what you want in the middleware stack.

What's in the box

Root package — constants and utilities

Everything you need to stop hardcoding strings in your HTTP code.

Content types: ContentTypeJSON, ContentTypeYAML, ContentTypeXML, ContentTypeHTML, ContentTypeOctetStream, ContentTypeMultipartFormData, ContentTypeApplicationFormURLEncoded, ContentTypeTextEventStream, and more.

Header names: Every header you'll ever use as a constant. HeaderNameAuthorization, HeaderNameContentType, HeaderNameXForwardedFor, HeaderNameXRequestID, all CORS headers, all security headers, all hop-by-hop headers (RFC 2616). Plus AuthSchemeBearer for the "Bearer " prefix.

Error handling: ErrorCode constants for every HTTP status (ErrorCodeBadRequest, ErrorCodeNotFound, etc.), ErrorCodeFromHTTPStatus() mapper, sentinel error vars (ErrBadRequest, ErrNotFound, etc.), and pre-built ErrorResponse structs ready to serialize.

Request utilities: GetClientIP(r) (respects X-Forwarded-ForX-Real-IPRemoteAddr), GetRequestID(r), content type checkers (IsRequestContentTypeJSON, etc.).

Response utilities: WriteJSON(w, statusCode, data) — pretty-printed JSON with proper headers.

Network & scheme constants: SchemeHTTP, SchemeHTTPS, NetworkTypeTCP, NetworkTypeUnix, etc.

server/ — HTTP server

Built on net/http with routing via Go 1.22+ ServeMux patterns.

srv, _ := server.New()                    // defaults from env vars
srv, _ := server.NewWithConfig(config)     // explicit config

Router with groups and middleware:

router := &server.Router{
    GlobalMiddlewares: []middleware.Middleware{
        middleware.RequestID(),
        middleware.Logger(),
        middleware.Recovery(),
        middleware.SecurityHeaders(),
        middleware.CORS(),
    },
    Static: []server.StaticRouteConfig{
        {Dir: "./static", Path: "/static"},
    },
    Groups: []server.GroupConfig{
        {
            Path: "/api/v1",
            Routes: []server.RouteConfig{
                {Method: http.MethodGet, Path: "/users", Handler: listUsers},
                {Method: http.MethodPost, Path: "/users", Handler: createUser},
            },
        },
        {
            Path: "/admin",
            Middlewares: []middleware.Middleware{
                middleware.BasicAuth(middleware.WithBasicAuthUsers(users)),
            },
            Routes: []server.RouteConfig{
                {Method: http.MethodGet, Path: "/stats", Handler: adminStats},
            },
        },
    },
}

srv.Start(ctx, router)

Built-in handlers: srv.HealthHandler, srv.EchoHandler, srv.FileUploadHandler(uploadsDir).

File uploads with configurable filename prepending (none, datetime, UUID) and custom post-processors.

Static file serving with path traversal protection, file caching, and directory indexing (HTML or JSON).

TLS out of the box — set HTTP_SERVER_TLSENABLED=true and point to cert/key files.

Config from environment:

Variable Default
HTTP_SERVER_LISTENADDRESS 127.0.0.1:8080
HTTP_SERVER_READTIMEOUT 15s
HTTP_SERVER_WRITETIMEOUT 30s
HTTP_SERVER_IDLETIMEOUT 60s
HTTP_SERVER_SHUTDOWNTIMEOUT 10s
HTTP_SERVER_MAXHEADERBYTES 1MB
HTTP_SERVER_TLSENABLED false
HTTP_SERVER_TLSLISTENADDRESS 127.0.0.1:8443
server/middleware/ — middleware stack

Every middleware uses slogging.GetLogger(ctx) for structured logging with context propagation. RequestID sets the request ID on the context logger, Logger adds method/path/ip — downstream code gets all fields for free.

RequestID — generates or extracts X-Request-ID, sets it on the context logger, adds it to the response header.

Logger — structured request/response logging with configurable log level, skip paths, extra fields, query/header inclusion.

middleware.Logger(
    middleware.WithLogLevel(slog.LevelDebug),
    middleware.WithSkipPaths("/health"),
    middleware.WithExtraFields(map[string]any{"service": "api"}),
    middleware.WithIncludeHeaders(aichteeteapee.HeaderNameAuthorization),
)

Recovery — catches panics, logs with stack trace, returns 500 JSON response. Fully configurable response body, status code, and content type.

BasicAuth — HTTP Basic Authentication with constant-time comparison, custom validators, skip paths, realm config.

CORS — full CORS with origin lists, methods, headers, credentials, max-age, preflight handling.

SecurityHeadersX-Content-Type-Options, X-Frame-Options, X-XSS-Protection, HSTS, Referrer-Policy, CSP. Each individually configurable or disableable.

Timeout — request deadline with 504 Gateway Timeout response. Presets: WithDefaultTimeout(), WithShortTimeout(), WithLongTimeout().

EnforceRequestContentType — reject requests with wrong Content-Type. Skips GET/HEAD/DELETE. Convenience: EnforceRequestContentTypeJSON().

server/prawxxey/ — HTTP request forwarding

Pronounced "proxy". Obviously.

Forward requests to upstream servers with optional response caching.

result, err := prawxxey.ForwardRequest(ctx, prawxxey.ForwardConfig{
    HTTPClient: http.DefaultClient,
    Cache:      myCache,            // nil = no caching
    CacheTTL:   5 * time.Minute,
    CacheKeyExcludeHeaders: map[string]struct{}{
        aichteeteapee.HeaderNameXRequestID: {},
    },
}, payload)
  • Sets X-Forwarded-For, X-Real-IP, X-Forwarded-Proto on upstream requests
  • Strips hop-by-hop headers per RFC 2616
  • Caches 2xx responses, skips errors
  • Cache key = sha256(method + url + headers + body) with configurable header exclusions
  • Custom cache key function via CacheKeyFn
  • Full structured logging: debug for hits/misses/forwards, warn for upstream 5xx, error for connection failures

RequestPayload.Hash() and RequestPayload.HashExcluding(excludeHeaders) for deterministic request fingerprinting.

server/dabluvee-es/ — WebSocket event system

Pronounced "WS" — because why stop at one wordplay.

A three-tier WebSocket architecture: HubClientConnection.

hub := wshub.NewHub("chat")

hub.RegisterEventHandler("chat.message", func(
    hub wshub.Hub, client *wshub.Client, event *dabluveees.Event,
) error {
    hub.BroadcastToAll(event)
    return nil
})

// HTTP upgrade endpoint
mux.HandleFunc("/ws/chat", wshub.UpgradeHandler(hub, clientID))

Events have UUID4 IDs, typed payloads (json.RawMessage — zero-copy), timestamps, and thread-safe metadata maps. Built-in types: EventTypeSystemLog, EventTypeShellExec, EventTypeEchoRequest/Reply, EventTypeError.

Hubs manage clients, route events to handlers, broadcast to all/specific/subscribed clients.

Clients represent logical users with multiple connections. Atomic state management, configurable buffer sizes, ping/pong heartbeat.

Connections wrap gorilla/websocket with write pumps, read pumps, graceful shutdown, and in-flight message tracking.

Unix Socket Bridge (wsunixbridge) — bridges WebSocket connections to Unix domain sockets for integrating external tools. Each connection gets dedicated reader/writer sockets.

echo/ — Echo framework wrapper

For when you want labstack/echo instead of net/http.

e, _ := echo.New("/api", swaggerYAML, middlewares)
e.Start(ctx)

Auto-serves OpenAPI spec at OASPath and Swagger UI at SwaggerUIPath. Config from HTTP_ECHO_LISTENADDRESS env var (defaults to 0.0.0.0:8080).

echo/middleware/ — Echo API middleware
middlewares := echomw.CreateDefaultAPIMiddleware(spec, echomw.BearerAuth(
    func(ctx context.Context, token string) error {
        return validateToken(ctx, token)
    },
))

OpenAPI request validation + panic recovery + Bearer token auth in one call.

oapi-codegen/middleware/ — OpenAPI validation for Echo

Wraps oapi-codegen/echo-middleware with structured error responses using aichteeteapee.ErrorResponse.

mw := oapimw.OapiValidatorMiddleware(spec)
// or with options:
mw := oapimw.OapiValidatorMiddlewareWithOptions(spec, opts)

Logging

All middleware and proxy code uses common-go/slogging for context-propagated structured logging.

The middleware chain builds up the logger progressively:

  1. RequestID adds requestId to the context logger
  2. Logger adds method, path, ip
  3. Any downstream code calls slogging.GetLogger(ctx) and gets all fields automatically

No explicit logger passing needed. Every log line from every middleware and handler automatically includes the full request context.

Development

make dep            # go mod tidy + vendor
make lint           # golangci-lint (strict)
make lint-fix       # lint + auto-fix
make test           # go test -race ./...
make test-coverage  # coverage with 85% minimum threshold

Smoke tests in server/.test-NOT PART OF PROJECT/:

cd "server/.test-NOT PART OF PROJECT"
bash run_tests_rapid.sh

Covers: health, API, static files, middleware, WebSocket stats, directory security, proxy forwarding, cache hits, logging context propagation, request ID headers, and log field verification.

License

MIT. See LICENSE.

Documentation

Index

Constants

View Source
const (
	ContentTypeJSON                      = "application/json"
	ContentTypeYAML                      = "application/yaml"
	ContentTypeTextPlain                 = "text/plain"
	ContentTypeXML                       = "application/xml"
	ContentTypeOctetStream               = "application/octet-stream"
	ContentTypeImageJPG                  = "image/jpeg"
	ContentTypeImagePNG                  = "image/png"
	ContentTypeMultipartFormData         = "multipart/form-data"
	ContentTypeApplicationFormURLEncoded = "application/x-www-form-urlencoded"
	ContentTypeHTML                      = "text/html"
	ContentTypeHTMLUTF8                  = "text/html; charset=UTF-8"
	ContentTypeTextEventStream           = "text/event-stream"

	// ContentTypeXYAML is the legacy unregistered MIME type for YAML.
	// Prefer ContentTypeYAML ("application/yaml") for new code.
	ContentTypeXYAML = "application/x-yaml"
)
View Source
const (
	// Common API path defaults.
	DefaultAPIRootPath       = "/api"
	StandardAPIOASPath       = "/openapi.yaml"
	StandardAPISwaggerUIPath = "/docs/*"

	// Echo server defaults.
	DefaultEchoListenAddress = "0.0.0.0:8080"

	// Server defaults.
	DefaultHTTPServerListenAddress     = "127.0.0.1:8080"
	DefaultHTTPServerReadTimeout       = 15 * time.Second
	DefaultHTTPServerReadHeaderTimeout = 10 * time.Second
	DefaultHTTPServerWriteTimeout      = 30 * time.Second
	DefaultHTTPServerIdleTimeout       = 60 * time.Second
	DefaultHTTPServerMaxHeaderBytes    = 1 << 20 // 1MB
	DefaultHTTPServerShutdownTimeout   = 10 * time.Second
	DefaultHTTPServerServiceName       = "http-server"

	// TLS Server defaults.
	DefaultHTTPServerTLSEnabled       = false
	DefaultHTTPServerTLSListenAddress = "127.0.0.1:8443"
	DefaultHTTPServerTLSCertFile      = ""
	DefaultHTTPServerTLSKeyFile       = ""

	// Request defaults.
	DefaultHTTPRequestTimeout = 30 * time.Second
	DefaultHTTPClientTimeout  = 30 * time.Second

	// CORS defaults.
	DefaultCORSAllowOriginAll = "*"
	DefaultCORSMaxAge         = 86400 // 24 hours in seconds

	// Security header default values.
	DefaultSecurityXContentTypeOptionsNoSniff = "nosniff"
	DefaultSecurityXFrameOptionsDeny          = "DENY"
	DefaultSecurityXXSSProtectionBlock        = "1; mode=block"
	DefaultSecurityStrictTransportSecurity    = "max-age=31536000; " +
		"includeSubDomains"
	DefaultSecurityReferrerPolicyStrictOrigin = "strict-origin" +
		"-when-cross-origin"

	// Authentication default values.
	DefaultBasicRealmName      = "restricted"
	DefaultUnauthorizedMessage = "Unauthorized"

	// File upload defaults.
	DefaultFileUploadMaxMemory = int64(32 << 20) // 32MB

	// WebSocket Client Configuration Defaults.
	DefaultWebSocketClientSendBufferSize  = 256
	DefaultWebSocketClientReadBufferSize  = 1024
	DefaultWebSocketClientWriteBufferSize = 1024
	DefaultWebSocketClientReadLimit       = 1024 * 1024 // 1MB
	DefaultWebSocketClientReadTimeout     = 60 * time.Second
	DefaultWebSocketClientWriteTimeout    = 10 * time.Second
	DefaultWebSocketClientPingInterval    = 54 * time.Second
	DefaultWebSocketClientPongTimeout     = 60 * time.Second

	// WebSocket Handler Configuration Defaults.
	DefaultWebSocketHandlerReadBufferSize    = 1024
	DefaultWebSocketHandlerWriteBufferSize   = 1024
	DefaultWebSocketHandlerHandshakeTimeout  = 45 * time.Second
	DefaultWebSocketHandlerEnableCompression = false
)
View Source
const (
	EnvVarNameHTTPServerListenAddress       = "HTTP_SERVER_LISTENADDRESS"
	EnvVarNameHTTPServerReadTimeout         = "HTTP_SERVER_READTIMEOUT"
	EnvVarNameHTTPServerReadHeaderTimeout   = "HTTP_SERVER_READHEADERTIMEOUT"
	EnvVarNameHTTPServerWriteTimeout        = "HTTP_SERVER_WRITETIMEOUT"
	EnvVarNameHTTPServerIdleTimeout         = "HTTP_SERVER_IDLETIMEOUT"
	EnvVarNameHTTPServerMaxHeaderBytes      = "HTTP_SERVER_MAXHEADERBYTES"
	EnvVarNameHTTPServerShutdownTimeout     = "HTTP_SERVER_SHUTDOWNTIMEOUT"
	EnvVarNameHTTPServerServiceName         = "HTTP_SERVER_SERVICENAME"
	EnvVarNameHTTPServerFileUploadMaxMemory = "HTTP_SERVER_FILEUPLOADMAXMEMORY"
	EnvVarNameHTTPServerTLSEnabled          = "HTTP_SERVER_TLSENABLED"
	EnvVarNameHTTPServerTLSListenAddress    = "HTTP_SERVER_TLSLISTENADDRESS"
	EnvVarNameHTTPServerTLSCertFile         = "HTTP_SERVER_TLSCERTFILE"
	EnvVarNameHTTPServerTLSKeyFile          = "HTTP_SERVER_TLSKEYFILE"
)
View Source
const (
	// Authentication headers.
	HeaderNameAuthorization = "Authorization"
	HeaderNameXAPIKey       = "X-Api-Key" //nolint: gosec

	// Authentication schemes.
	AuthSchemeBearer = "Bearer "

	// Content headers.
	HeaderNameContentType    = "Content-Type"
	HeaderNameContentLength  = "Content-Length"
	HeaderNameAccept         = "Accept"
	HeaderNameAcceptEncoding = "Accept-Encoding"

	// Request tracking.
	HeaderNameXRequestID     = "X-Request-ID"
	HeaderNameXCorrelationID = "X-Correlation-ID"

	// Client info.
	HeaderNameUserAgent       = "User-Agent"
	HeaderNameXForwardedFor   = "X-Forwarded-For"
	HeaderNameXForwardedProto = "X-Forwarded-Proto"
	HeaderNameXForwardedHost  = "X-Forwarded-Host"
	HeaderNameXRealIP         = "X-Real-IP"
	HeaderNameXClientID       = "X-Client-ID"

	// CORS headers.
	HeaderNameOrigin                        = "Origin"
	HeaderNameAccessControlAllowOrigin      = "Access-Control-Allow-Origin"
	HeaderNameAccessControlAllowMethods     = "Access-Control-Allow-Methods"
	HeaderNameAccessControlAllowHeaders     = "Access-Control-Allow-Headers"
	HeaderNameAccessControlExposeHeaders    = "Access-Control-Expose-Headers"
	HeaderNameAccessControlAllowCredentials = "Access-Control-Allow-Credentials"
	HeaderNameAccessControlMaxAge           = "Access-Control-Max-Age"
	HeaderNameVary                          = "Vary"

	// Cache control.
	HeaderNameCacheControl = "Cache-Control"
	HeaderNameETag         = "ETag"
	HeaderNameIfNoneMatch  = "If-None-Match"

	// Hop-by-hop headers (RFC 2616 section 13.5.1).
	// These must not be forwarded by proxies.
	HeaderNameConnection         = "Connection"
	HeaderNameKeepAlive          = "Keep-Alive"
	HeaderNameProxyAuthenticate  = "Proxy-Authenticate"
	HeaderNameProxyAuthorization = "Proxy-Authorization"
	HeaderNameTE                 = "Te"
	HeaderNameTrailers           = "Trailers"
	HeaderNameTransferEncoding   = "Transfer-Encoding"
	HeaderNameUpgrade            = "Upgrade"

	// Security headers.
	HeaderNameStrictTransportSecurity = "Strict-Transport-Security"
	HeaderNameXContentTypeOptions     = "X-Content-Type-Options"
	HeaderNameXFrameOptions           = "X-Frame-Options"
	HeaderNameXXSSProtection          = "X-XSS-Protection"
	HeaderNameReferrerPolicy          = "Referrer-Policy"
	HeaderNameContentSecurityPolicy   = "Content-Security-Policy"
	HeaderNameWWWAuthenticate         = "WWW-Authenticate"
)
View Source
const (
	// Client identifiers.
	FieldClientID = "clientID"

	// WebSocket-specific fields.
	FieldConnectionID = "connectionID"

	// Event-related fields.
	FieldEventType = "eventType"
	FieldEventID   = "eventID"

	// Hub and system identifiers.
	FieldHubName = "hubName"

	// Error and performance fields.
	FieldTotalConns   = "totalConns"
	FieldTotalClients = "totalClients"
	FieldBufferSize   = "bufferSize"

	// Network and connection fields.
	FieldRemoteAddr = "remoteAddr"
	FieldUserAgent  = "userAgent"
	FieldOrigin     = "origin"

	// WebSocket close fields.
	FieldCloseCode = "closeCode"
	FieldCloseText = "closeText"

	// Configuration fields.
	FieldReadBufferSize    = "readBufferSize"
	FieldWriteBufferSize   = "writeBufferSize"
	FieldHandshakeTimeout  = "handshakeTimeout"
	FieldEnableCompression = "enableCompression"
	FieldOldReadSize       = "oldReadSize"
	FieldOldWriteSize      = "oldWriteSize"
	FieldNewReadSize       = "newReadSize"
	FieldNewWriteSize      = "newWriteSize"

	// Server and endpoint fields.
	FieldEndpoint = "endpoint"

	// File system and data fields.
	FieldPath  = "path"
	FieldBytes = "bytes"
)
View Source
const (
	// URI schemes.
	SchemeHTTP  = "http"
	SchemeHTTPS = "https"

	// Network types for net.Listen and similar functions.
	NetworkTypeTCP        = "tcp"
	NetworkTypeTCP4       = "tcp4"
	NetworkTypeTCP6       = "tcp6"
	NetworkTypeUDP        = "udp"
	NetworkTypeUDP4       = "udp4"
	NetworkTypeUDP6       = "udp6"
	NetworkTypeUnix       = "unix"
	NetworkTypeUnixgram   = "unixgram"
	NetworkTypeUnixpacket = "unixpacket"
)
View Source
const (
	FileNameIndexHTML = "index.html"
)

Variables

View Source
var (
	// File and path errors.
	ErrorResponseFileNotFound = ErrorResponse{
		Code:    ErrorCodeFileNotFound,
		Message: "File not found",
	}

	ErrorResponseDirectoryListingNotSupported = ErrorResponse{
		Code:    ErrorCodeDirectoryListingNotSupported,
		Message: "Directory listing is not supported",
	}

	ErrorResponsePathTraversalDenied = ErrorResponse{
		Code:    ErrorCodePathTraversalDenied,
		Message: "Path traversal denied",
	}

	// Standard HTTP errors.
	ErrorResponseNotFound = ErrorResponse{
		Code:    ErrorCodeNotFound,
		Message: "Not found",
	}

	ErrorResponseEndpointNotFound = ErrorResponse{
		Code:    ErrorCodeEndpointNotFound,
		Message: "Endpoint not found",
	}

	ErrorResponseMethodNotAllowed = ErrorResponse{
		Code:    ErrorCodeMethodNotAllowed,
		Message: "Method not allowed",
	}

	ErrorResponseConflict = ErrorResponse{
		Code:    ErrorCodeConflict,
		Message: "Conflict",
	}

	ErrorResponseGone = ErrorResponse{
		Code:    ErrorCodeGone,
		Message: "Gone",
	}

	ErrorResponseUnprocessableEntity = ErrorResponse{
		Code:    ErrorCodeUnprocessableEntity,
		Message: "Unprocessable entity",
	}

	ErrorResponseTooManyRequests = ErrorResponse{
		Code:    ErrorCodeTooManyRequests,
		Message: "Too many requests",
	}

	ErrorResponseNotImplemented = ErrorResponse{
		Code:    ErrorCodeNotImplemented,
		Message: "Not implemented",
	}

	ErrorResponseBadGateway = ErrorResponse{
		Code:    ErrorCodeBadGateway,
		Message: "Bad gateway",
	}

	ErrorResponseServiceUnavailable = ErrorResponse{
		Code:    ErrorCodeServiceUnavailable,
		Message: "Service unavailable",
	}

	ErrorResponseGatewayTimeout = ErrorResponse{
		Code:    ErrorCodeGatewayTimeout,
		Message: "Gateway timeout",
	}

	// User-related errors.
	ErrorResponseMissingUserID = ErrorResponse{
		Code:    ErrorCodeMissingUserID,
		Message: "User ID is required",
	}

	ErrorResponseInvalidUserID = ErrorResponse{
		Code:    ErrorCodeInvalidUserID,
		Message: "Invalid user ID format",
	}

	// Generic errors.
	ErrorResponseValidationFailed = ErrorResponse{
		Code:    ErrorCodeValidationFailed,
		Message: "Validation failed",
	}

	ErrorResponseBadRequest = ErrorResponse{
		Code:    ErrorCodeBadRequest,
		Message: "Bad request",
	}

	ErrorResponseUnauthorized = ErrorResponse{
		Code:    ErrorCodeUnauthorized,
		Message: "Unauthorized",
	}

	ErrorResponseForbidden = ErrorResponse{
		Code:    ErrorCodeForbidden,
		Message: "Access forbidden",
	}

	ErrorResponseInternalServerError = ErrorResponse{
		Code:    ErrorCodeInternalServerError,
		Message: "Internal server error",
	}

	// Content type errors.
	ErrorResponseMissingContentType = ErrorResponse{
		Code:    ErrorCodeMissingContentType,
		Message: "Content-Type header is required",
	}

	ErrorResponseUnsupportedContentType = ErrorResponse{
		Code:    ErrorCodeUnsupportedContentType,
		Message: "Unsupported content type",
	}

	// File upload errors.
	ErrorResponseInvalidMultipartForm = ErrorResponse{
		Code:    ErrorCodeInvalidMultipartForm,
		Message: "Invalid multipart form",
	}

	ErrorResponseNoFileProvided = ErrorResponse{
		Code:    ErrorCodeNoFileProvided,
		Message: "No file provided",
	}

	ErrorResponseFileSaveFailed = ErrorResponse{
		Code:    ErrorCodeFileSaveFailed,
		Message: "Failed to save file",
	}
)
View Source
var (
	ErrBadRequest          = errors.New("bad request")
	ErrUnauthorized        = errors.New("unauthorized")
	ErrNotAuthenticated    = errors.New("not authenticated")
	ErrForbidden           = errors.New("forbidden")
	ErrNotFound            = errors.New("not found")
	ErrMethodNotAllowed    = errors.New("method not allowed")
	ErrConflict            = errors.New("conflict")
	ErrGone                = errors.New("gone")
	ErrUnprocessableEntity = errors.New("unprocessable entity")
	ErrTooManyRequests     = errors.New("too many requests")
)

4xx Client Errors.

View Source
var (
	ErrInternalServer     = errors.New("internal server error")
	ErrBadGateway         = errors.New("bad gateway")
	ErrServiceUnavailable = errors.New("service unavailable")
	ErrGatewayTimeout     = errors.New("gateway timeout")
)

5xx Server Errors.

Functions

func GetClientIP

func GetClientIP(r *http.Request) string

func GetDefaultCORSAllowHeaders

func GetDefaultCORSAllowHeaders() string

func GetDefaultCORSAllowMethods

func GetDefaultCORSAllowMethods() string

func GetDefaultWebSocketCheckOrigin

func GetDefaultWebSocketCheckOrigin(_ *http.Request) bool

GetDefaultWebSocketCheckOrigin is the default origin checker for WebSocket connections. WARNING: This allows all origins - configure for your security needs in production.

func GetRequestID

func GetRequestID(r *http.Request) string

func IsRequestContentType

func IsRequestContentType(r *http.Request, expectedContentType string) bool

Handles charset parameters and is case-insensitive.

func IsRequestContentTypeApplicationFormURLEncoded

func IsRequestContentTypeApplicationFormURLEncoded(r *http.Request) bool

func IsRequestContentTypeJSON

func IsRequestContentTypeJSON(r *http.Request) bool

func IsRequestContentTypeMultipartFormData

func IsRequestContentTypeMultipartFormData(r *http.Request) bool

func IsRequestContentTypeXML

func IsRequestContentTypeXML(r *http.Request) bool

func WriteJSON

func WriteJSON(
	w http.ResponseWriter,
	statusCode int,
	data any,
)

Types

type ContextKey

type ContextKey string
const (
	ContextKeyRequestID ContextKey = "requestId"
	ContextKeyUser      ContextKey = "user"
)

type ErrorCode

type ErrorCode = string
const (
	// Standard HTTP error codes.
	ErrorCodeBadRequest          ErrorCode = "BAD_REQUEST"
	ErrorCodeUnauthorized        ErrorCode = "UNAUTHORIZED"
	ErrorCodeForbidden           ErrorCode = "FORBIDDEN"
	ErrorCodeNotFound            ErrorCode = "NOT_FOUND"
	ErrorCodeMethodNotAllowed    ErrorCode = "METHOD_NOT_ALLOWED"
	ErrorCodeConflict            ErrorCode = "CONFLICT"
	ErrorCodeGone                ErrorCode = "GONE"
	ErrorCodeUnprocessableEntity ErrorCode = "UNPROCESSABLE_ENTITY"
	ErrorCodeTooManyRequests     ErrorCode = "TOO_MANY_REQUESTS"
	ErrorCodeInternalServerError ErrorCode = "INTERNAL_SERVER_ERROR"
	ErrorCodeNotImplemented      ErrorCode = "NOT_IMPLEMENTED"
	ErrorCodeBadGateway          ErrorCode = "BAD_GATEWAY"
	ErrorCodeServiceUnavailable  ErrorCode = "SERVICE_UNAVAILABLE"
	ErrorCodeGatewayTimeout      ErrorCode = "GATEWAY_TIMEOUT"

	// Semantic error codes.
	ErrorCodeValidationFailed ErrorCode = "VALIDATION_FAILED"
	ErrorCodeRateLimited      ErrorCode = "RATE_LIMITED"

	// Endpoint / routing errors.
	ErrorCodeEndpointNotFound ErrorCode = "ENDPOINT_NOT_FOUND"

	// File and path errors.
	ErrorCodeFileNotFound                 ErrorCode = "FILE_NOT_FOUND"
	ErrorCodeDirectoryListingNotSupported ErrorCode = "DIRECTORY_LISTING_" +
		"NOT_SUPPORTED"
	ErrorCodePathTraversalDenied ErrorCode = "PATH_TRAVERSAL_DENIED"

	// User-related errors.
	ErrorCodeMissingUserID ErrorCode = "MISSING_USER_ID"
	ErrorCodeInvalidUserID ErrorCode = "INVALID_USER_ID"

	// Content type errors.
	ErrorCodeMissingContentType     ErrorCode = "MISSING_CONTENT_TYPE"
	ErrorCodeUnsupportedContentType ErrorCode = "UNSUPPORTED_CONTENT_TYPE"

	// File upload errors.
	ErrorCodeInvalidMultipartForm ErrorCode = "INVALID_MULTIPART_FORM"
	ErrorCodeNoFileProvided       ErrorCode = "NO_FILE_PROVIDED"
	ErrorCodeFileSaveFailed       ErrorCode = "FILE_SAVE_FAILED"
)

func ErrorCodeFromHTTPStatus added in v1.1.0

func ErrorCodeFromHTTPStatus(status int) ErrorCode

Returns ErrorCodeInternalServerError for unmapped status codes.

type ErrorResponse

type ErrorResponse struct {
	Code    string `json:"code,omitempty"`
	Message string `json:"message,omitempty"`
	Details any    `json:"details,omitempty"`
}

Directories

Path Synopsis
oapi-codegen

Jump to

Keyboard shortcuts

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