aichteeteapee

package module
v1.1.1 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" - because sometimes the best fucking code comes with wordplay.

aichteeteapee is a batteries-included HTTP utilities library that gets you from go mod init to working server with minimal configuration. Built on the philosophy of sane defaults, zero boilerplate, and easy customization.

Perfect for:

  • 🚀 Rapid prototyping with solid foundations
  • 🏗️ Microservices that need HTTP + WebSocket capabilities
  • 📡 APIs requiring file uploads, static serving, and real-time features
  • 🛠️ Any Go project that wants HTTP functionality without the fucking boilerplate

Table of Contents

Quick Start - Zero to Hero

Minimal example:

package main

import (
    "context"
    "net/http"
    "github.com/psyb0t/aichteeteapee/server"
)

func main() {
    srv, _ := server.New()
    router := server.Router{
        Groups: []server.GroupConfig{{
            Path: "/",
            Routes: []server.RouteConfig{
                {Method: "GET", Path: "/", Handler: func(w http.ResponseWriter, r *http.Request) {
                    w.Write([]byte("Hello, World!"))
                }},
            },
        }},
    }
    srv.Start(context.Background(), router)
}

With features:

package main

import (
    "context"
    "log"
    "net/http"

    "github.com/psyb0t/aichteeteapee/server"
    "github.com/psyb0t/aichteeteapee/server/middleware"
    "github.com/psyb0t/aichteeteapee/server/dabluvee-es/wshub"
)

func main() {
    // Create server with sane defaults
    srv, err := server.New()
    if err != nil {
        log.Fatal("Failed to create server:", err)
    }

    // Create WebSocket hub for real-time features
    chatHub := wshub.NewHub("chat")

    // Build router with all the features
    router := server.Router{
        Middlewares: []middleware.Middleware{
            middleware.Logger(),          // Request logging
            middleware.Recovery(),        // Panic recovery
            middleware.CORS(),           // Smart CORS handling
            middleware.SecurityHeaders(), // Security headers
        },
        Groups: []server.GroupConfig{
            {
                Path: "/",
                Routes: []server.RouteConfig{
                    {Method: "GET", Path: "/", Handler: homeHandler},
                    {Method: "GET", Path: "/health", Handler: srv.HealthHandler()},
                    {Method: "POST", Path: "/upload", Handler: srv.FileUploadHandler("./uploads")},
                },
            },
            {
                Path: "/ws",
                Routes: []server.RouteConfig{
                    {Method: "GET", Path: "/chat", Handler: wshub.UpgradeHandler(chatHub)},
                },
            },
        },
        Static: []server.StaticRouteConfig{
            {
                URLPath:    "/static",
                LocalPath:  "./public",
                DirectoryIndexingType: server.DirectoryIndexingTypeHTML,
            },
        },
    }

    // Start server - HTTP on :8080, HTTPS on :8443, graceful shutdown
    log.Fatal(srv.Start(context.Background(), router))
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.Write([]byte(`{"message": "Hello, World!", "status": "ok"}`))
}

That's it! You now have:

  • ✅ HTTP + HTTPS servers running
  • ✅ CORS, security headers, request logging
  • ✅ File uploads with processing hooks & filename options
  • ✅ Static file serving with directory browsing (HTML/JSON)
  • ✅ WebSocket hub for real-time features with event metadata
  • ✅ Request ID generation & extraction utilities
  • ✅ Content-type enforcement middleware
  • ✅ Timeout middleware with presets (short/default/long)
  • ✅ Granular security header control
  • ✅ Health checks and echo endpoints
  • ✅ Unix socket bridge for external tool integration
  • ✅ Graceful shutdown handling

Configuration

Environment Variables
# Server settings
HTTP_SERVER_LISTENADDRESS=127.0.0.1:8080
HTTP_SERVER_TLSLISTENADDRESS=127.0.0.1:8443
HTTP_SERVER_SERVICENAME=MyAPI

# Security
HTTP_SERVER_TLSENABLED=true
HTTP_SERVER_TLSCERTFILE=./certs/server.crt
HTTP_SERVER_TLSKEYFILE=./certs/server.key

# Timeouts (durations)
HTTP_SERVER_READTIMEOUT=30s
HTTP_SERVER_READHEADERTIMEOUT=10s
HTTP_SERVER_WRITETIMEOUT=30s
HTTP_SERVER_IDLETIMEOUT=60s
HTTP_SERVER_MAXHEADERBYTES=1048576
HTTP_SERVER_SHUTDOWNTIMEOUT=30s

# File uploads
HTTP_SERVER_FILEUPLOADMAXMEMORY=52428800  # 50MB in bytes
Programmatic Config
srv, err := server.NewWithConfig(server.Config{
    ListenAddress:       "0.0.0.0:8080",
    TLSListenAddress:    "0.0.0.0:8443",
    ServiceName:         "ProductionAPI",
    ReadTimeout:         30 * time.Second,
    ReadHeaderTimeout:   10 * time.Second,
    WriteTimeout:        30 * time.Second,
    IdleTimeout:         60 * time.Second,
    MaxHeaderBytes:      1 << 20, // 1MB
    ShutdownTimeout:     30 * time.Second,
    FileUploadMaxMemory: 100 << 20, // 100MB
    TLSEnabled:          true,
    TLSCertFile:         "/etc/ssl/certs/api.crt",
    TLSKeyFile:          "/etc/ssl/private/api.key",
})

Key Features

🎯 Zero-Config Defaults
  • Secure defaults: HTTPS, security headers, CORS, timeouts
  • Graceful shutdown: Proper resource cleanup and connection draining
  • Structured logging: Consistent field names with request tracing
  • Health checks: Built-in /health and /echo endpoints
🌐 Advanced HTTP Server
  • Route groups: Organize routes with shared middleware and configuration
  • Static files: Automatic serving with configurable directory indexing
  • File uploads: Built-in multipart handling with postprocessing hooks
  • Middleware system: Composable, reusable middleware with proper ordering
🛡️ Built-in Middleware
  • CORS: Cross-origin request handling for browser compatibility
  • Basic Auth: Simple authentication with configurable realms
  • Security Headers: HSTS, CSP, X-Frame-Options, and more
  • Logger: Structured request logging with configurable fields
  • Recovery: Panic recovery with stack traces and custom handlers
  • Request ID: Automatic generation and extraction utilities
  • Timeout: Configurable timeouts with presets (short/default/long)
  • Content-Type Enforcement: API protection with configurable types
WebSocket Systems

Note: WebSocket functionality lives in the dabluveees package - pronounced "dub-ell-vee-ess" (double-v-s = WS). More wordplay because memorable imports are better than boring ones.

WebSocket Hub (for real-time applications):

  • Multi-client management: Automatic connection lifecycle handling
  • Event-driven architecture: Type-safe event system with JSON marshaling
  • Broadcast capabilities: Send to all clients, specific clients, or groups
  • Connection metadata: Per-connection data storage and retrieval

Unix Socket Bridge (for external tool integration):

  • Bidirectional bridge: WebSocket ↔ Unix domain sockets
  • External tool integration: Shell scripts, CLI tools, other processes
  • File-based communication: Simple read/write operations
  • Tool chaining: Connect WebSocket apps to existing Unix toolchain
🛠️ Developer Experience
  • Sane defaults: Works out of the box, customize when needed
  • File upload options: UUID/DateTime/None filename prepending
  • Event metadata system: Thread-safe WebSocket event enrichment
  • Error handling: Proper HTTP status codes and JSON responses
  • Middleware composability: Easy to chain and customize

Advanced Usage

Custom Middleware
// Create your own middleware
func AuthMiddleware(secret string) middleware.Middleware {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            token := r.Header.Get("Authorization")
            if !validateToken(token, secret) {
                http.Error(w, "Unauthorized", http.StatusUnauthorized)
                return
            }
            next.ServeHTTP(w, r)
        })
    }
}

// Use in route groups
{
    Path: "/api/protected",
    Middlewares: []middleware.Middleware{
        AuthMiddleware("your-secret-key"),
    },
    Routes: []server.RouteConfig{
        {Method: "GET", Path: "/profile", Handler: profileHandler},
    },
}
WebSocket Events
// Define your event types
const (
    EventTypeChatMessage dabluveees.EventType = "chat.message"
    EventTypeUserJoin    dabluveees.EventType = "user.join"
    EventTypeUserLeave   dabluveees.EventType = "user.leave"
)

// Create event handlers
chatHub := wshub.NewHub("chat")
chatHub.RegisterEventHandlers(map[dabluveees.EventType]wshub.EventHandler{
    EventTypeChatMessage: func(hub wshub.Hub, client *wshub.Client, event *dabluveees.Event) error {
        // Parse message data
        var messageData struct {
            Text   string `json:"text"`
            UserID string `json:"userId"`
        }
        if err := json.Unmarshal(event.Data, &messageData); err != nil {
            return err
        }

        // Add timestamp and broadcast
        event.Metadata.Set("timestamp", time.Now().Unix())
        hub.BroadcastToAll(event)
        return nil
    },
})
Unix Socket Bridge - External Tool Integration
// Unix socket bridge for external tool integration
import "github.com/psyb0t/aichteeteapee/server/dabluvee-es/wsunixbridge"

// Create Unix bridge handler
bridgeHandler := wsunixbridge.NewUpgradeHandler(
    "./sockets",  // Directory for Unix socket files
    func(connection *wsunixbridge.Connection) error {
        log.Printf("Unix bridge connection established: %s", connection.ID)
        log.Printf("Writer socket: %s", connection.WriterUnixSock.Path)
        log.Printf("Reader socket: %s", connection.ReaderUnixSock.Path)
        return nil
    },
)

// Add to routes
{Method: "GET", Path: "/unixsock", Handler: bridgeHandler}

// External tools can now:
// 1. Connect to writer socket to receive WebSocket data
// 2. Write to reader socket to send data to WebSocket
//
// Example: echo "Hello from external tool" | socat - UNIX-CONNECT:./sockets/connection-id_input
File Upload Processing
// Advanced file upload configuration
uploadHandler := srv.FileUploadHandler("./uploads",
    // Custom postprocessor for file processing
    server.WithFileUploadHandlerPostprocessor(func(
        response map[string]any,
        request *http.Request,
    ) (map[string]any, error) {
        // Add custom metadata to upload response
        response["processed_at"] = time.Now().Unix()
        response["user_ip"] = request.RemoteAddr
        return response, nil
    }),

    // Filename prepending options
    server.WithFilenamePrependType(server.FilenamePrependTypeDateTime), // Y_M_D_H_I_S_
    // Alternative: server.FilenamePrependTypeUUID (default)
    // Alternative: server.FilenamePrependTypeNone
)
Advanced Middleware Features
import (
    "github.com/psyb0t/aichteeteapee/server/middleware"
    "github.com/sirupsen/logrus"
)

// Request ID middleware with utility functions
router := server.Router{
    Middlewares: []middleware.Middleware{
        middleware.RequestID(), // Automatic request ID generation
    },
    Groups: []server.GroupConfig{
        {
            Path: "/api",
            Routes: []server.RouteConfig{
                {
                    Method: "GET",
                    Path: "/status",
                    Handler: func(w http.ResponseWriter, r *http.Request) {
                        // Extract request ID from context
                        reqID := middleware.GetRequestID(r)

                        response := map[string]string{
                            "status":     "ok",
                            "request_id": reqID,
                        }
                        json.NewEncoder(w).Encode(response)
                    },
                },
            },
        },
    },
}

// Content-Type enforcement for APIs
apiGroup := server.GroupConfig{
    Path: "/api",
    Middlewares: []middleware.Middleware{
        // Only allow JSON requests
        middleware.EnforceRequestContentType("application/json"),
        // Alternative: allow multiple types
        // middleware.EnforceRequestContentType("application/json", "application/xml"),
        // Shortcut for JSON-only APIs
        // middleware.EnforceRequestContentTypeJSON(),
    },
    Routes: []server.RouteConfig{
        {Method: "POST", Path: "/users", Handler: createUserHandler},
    },
}

// Timeout middleware with presets
timeoutGroup := server.GroupConfig{
    Path: "/slow-api",
    Middlewares: []middleware.Middleware{
        middleware.Timeout(
            middleware.WithLongTimeout(), // 5 minutes
            // Alternative presets:
            // middleware.WithShortTimeout(),   // 5 seconds
            // middleware.WithDefaultTimeout(), // 30 seconds
            // middleware.WithTimeout(2 * time.Minute), // Custom
        ),
    },
    Routes: []server.RouteConfig{
        {Method: "POST", Path: "/batch-process", Handler: batchProcessHandler},
    },
}

// Security headers with granular control
secureGroup := server.GroupConfig{
    Path: "/secure",
    Middlewares: []middleware.Middleware{
        middleware.SecurityHeaders(
            // Enable specific headers
            middleware.WithXContentTypeOptions("nosniff"),
            middleware.WithXFrameOptions("DENY"),
            middleware.WithStrictTransportSecurity("max-age=31536000; includeSubDomains"),

            // Disable unwanted headers
            middleware.DisableXXSSProtection(), // If you handle XSS at app level
            middleware.DisableCSP(),            // If you have custom CSP
        ),
    },
}
Enhanced WebSocket Events
import "github.com/psyb0t/aichteeteapee/server/dabluvee-es"

// Event creation with metadata and utility methods
hub := wshub.NewHub("notifications")

hub.RegisterEventHandler(EventTypeNewMessage, func(hub wshub.Hub, client *wshub.Client, event *dabluveees.Event) error {
    // Add metadata to events
    enrichedEvent := event.
        WithMetadata("server_id", "api-01").
        WithMetadata("processing_time", time.Now().Unix()).
        WithTimestamp(time.Now().Unix()) // Override timestamp

    // Check if event is recent (within last 60 seconds)
    if enrichedEvent.IsRecent(60) {
        // Get event time as Go time.Time
        eventTime := enrichedEvent.GetTime()
        log.Printf("Processing recent event from %v", eventTime)

        // Broadcast with enriched metadata
        hub.BroadcastToAll(&enrichedEvent)
    }

    return nil
})

// Built-in event types available
const (
    // System events
    dabluveees.EventTypeSystemLog   // "system.log"
    dabluveees.EventTypeShellExec   // "shell.exec"
    dabluveees.EventTypeEchoRequest // "echo.request"
    dabluveees.EventTypeEchoReply   // "echo.reply"
    dabluveees.EventTypeError       // "error"
)

Security Warnings ⚠️

READ THIS SHIT CAREFULLY - Security is not a fucking joke:

🔥 CRITICAL - Authentication & Authorization
  • NEVER run without authentication in production
  • ALWAYS validate user permissions before accessing resources
  • USE HTTPS in production - HTTP is not secure
  • IMPLEMENT proper session management and token validation
🔒 File Upload Security
  • VALIDATE file types and sizes - don't trust client data
  • SCAN uploads for malware before processing
  • STORE uploads outside web root to prevent direct access
  • LIMIT file extensions and use whitelist, not blacklist
🛡️ Path Traversal Protection
  • Library includes protection, but ALWAYS validate custom file paths
  • NEVER trust user input for file system operations
  • USE absolute paths and proper validation for file access
🚨 WebSocket Security
  • AUTHENTICATE WebSocket connections - they bypass normal HTTP auth
  • VALIDATE all event data - treat it as untrusted input
  • IMPLEMENT rate limiting for WebSocket messages
  • MONITOR connection counts to prevent DoS attacks
🔐 Production Checklist
  • HTTPS configured with valid certificates
  • Security headers properly configured
  • Authentication middleware on protected routes
  • File upload validation and scanning
  • Proper error handling (don't leak internal info)
  • Request logging and monitoring in place
  • Rate limiting configured

TODO

WebSocket Hub Enhancements
  • Connection Lifecycle Callbacks: Add support for third-party apps to register "on connected" and "on disconnected" callbacks for WebSocket connections
    • OnClientConnected callback when a new client connects
    • OnClientDisconnected callback when a client disconnects
    • OnConnectionEstablished callback for individual connections
    • OnConnectionClosed callback for individual connections

License

MIT License. See LICENSE file for details.

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