aichteeteapee

package module
v1.5.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: 10 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 secure defaults and zero boilerplate.

srv, _ := serbewr.New()

router := &serbewr.Router{
    GlobalMiddlewares: []middleware.Middleware{
        middleware.RequestID(),
        middleware.Logger(),
        middleware.Recovery(),
        middleware.SecurityHeaders(),
        middleware.CORS(),
    },
    Groups: []serbewr.GroupConfig{{
        Path: "/",
        Routes: []serbewr.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)

Security

Secure by default. CORS blocks unknown origins, WebSocket validates Origin against Host, file uploads sanitize filenames (no path traversal), uploaded files get 0600 permissions and won't overwrite existing files, request IDs are validated, proxy responses are size-limited, sensitive headers are filtered from echo responses.

Need to skip all that during local dev? One call:

aichteeteapee.FuckSecurity()

CORS allows all origins, WebSocket accepts any origin. Call aichteeteapee.UnfuckSecurity() to go back.

Per-component overrides without global dev mode:

middleware.CORS(middleware.WithAllowAllOrigins())

wshub.UpgradeHandler(hub,
    wshub.WithUpgradeHandlerCheckOrigin(
        aichteeteapee.GetPermissiveWebSocketCheckOrigin,
    ),
)

What's in the box

Root package — constants and utilities

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

  • Content typesContentTypeJSON, ContentTypeYAML, ContentTypeHTML, ContentTypeMultipartFormData, etc.
  • Header names — every header as a constant: authentication, content negotiation, CORS, cache, security, hop-by-hop, rate limiting, WebSocket. Plus AuthSchemeBearer and AuthSchemeBasic for scheme prefixes.
  • Error handlingErrorCode constants for every HTTP status, ErrorCodeFromHTTPStatus() mapper, sentinel errors (ErrBadRequest, ErrNotFound, ...), pre-built ErrorResponse structs.
  • Request utilitiesGetClientIP(r), GetRequestID(r), content type checkers (IsRequestContentTypeJSON, etc.).
  • Response utilitiesWriteJSON(w, statusCode, data).
  • Network constantsSchemeHTTP, SchemeHTTPS, NetworkTypeTCP, NetworkTypeUnix, etc.
serbewr/ — HTTP server

Pronounced "server". Built on net/http with Go 1.22+ ServeMux routing, grouped routes with per-group middleware, built-in handlers (health, echo, file upload), static file serving with directory indexing, TLS, and env-based config.

serbewr/middleware/ — middleware stack

RequestID, Logger, Recovery, BasicAuth, CORS, SecurityHeaders, Timeout, EnforceRequestContentType. All use context-propagated structured logging.

serbewr/prawxxey/ — HTTP request forwarding

Pronounced "proxy". Forward requests upstream with optional response caching, hop-by-hop header stripping, response size limits, and deterministic request fingerprinting.

serbewr/dabluvee-es/ — WebSocket event system

Pronounced "WS". Three-tier architecture (Hub -> Client -> Connection) with typed events, handler registration, broadcast, and a Unix socket bridge for external tool integration.

echo/ — Echo framework integration

Echo wrapper with auto-served OpenAPI specs and Swagger UI. Includes Bearer auth middleware and OpenAPI request validation via oapi-codegen.

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. Downstream code calls slogging.GetLogger(ctx) and gets all fields automatically

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 minimum threshold

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.
	HeaderNameAuthorization   = "Authorization"
	HeaderNameXAPIKey         = "X-Api-Key" //nolint: gosec
	HeaderNameWWWAuthenticate = "WWW-Authenticate"

	// Authentication schemes.
	AuthSchemeBearer = "Bearer "
	AuthSchemeBasic  = "Basic "

	// Session/cookie.
	HeaderNameCookie    = "Cookie"
	HeaderNameSetCookie = "Set-Cookie"

	// Content negotiation.
	HeaderNameContentType        = "Content-Type"
	HeaderNameContentLength      = "Content-Length"
	HeaderNameContentDisposition = "Content-Disposition"
	HeaderNameContentEncoding    = "Content-Encoding"
	HeaderNameContentLanguage    = "Content-Language"
	HeaderNameContentLocation    = "Content-Location"
	HeaderNameContentRange       = "Content-Range"
	HeaderNameAccept             = "Accept"
	HeaderNameAcceptCharset      = "Accept-Charset"
	HeaderNameAcceptEncoding     = "Accept-Encoding"
	HeaderNameAcceptLanguage     = "Accept-Language"
	HeaderNameAcceptRanges       = "Accept-Ranges"

	// 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"
	HeaderNameHost            = "Host"
	HeaderNameReferer         = "Referer"

	// CORS.
	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"
	HeaderNameAccessControlRequestMethod    = "Access-Control-Request-Method"
	HeaderNameAccessControlRequestHeaders   = "Access-Control-Request-Headers"
	HeaderNameVary                          = "Vary"

	// Cache control.
	HeaderNameCacheControl = "Cache-Control"
	HeaderNamePragma       = "Pragma"
	HeaderNameExpires      = "Expires"
	HeaderNameETag         = "ETag"
	HeaderNameIfNoneMatch  = "If-None-Match"
	HeaderNameIfMatch      = "If-Match"
	HeaderNameIfModSince   = "If-Modified-Since"
	HeaderNameIfUnmodSince = "If-Unmodified-Since"
	HeaderNameLastModified = "Last-Modified"
	HeaderNameAge          = "Age"

	// Hop-by-hop (RFC 2616 section 13.5.1) — 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.
	HeaderNameStrictTransportSecurity = "Strict-Transport-Security"
	HeaderNameXContentTypeOptions     = "X-Content-Type-Options"
	HeaderNameXFrameOptions           = "X-Frame-Options"
	HeaderNameXXSSProtection          = "X-XSS-Protection"
	HeaderNameReferrerPolicy          = "Referrer-Policy"
	HeaderNameContentSecurityPolicy   = "Content-Security-Policy"
	HeaderNamePermissionsPolicy       = "Permissions-Policy"
	HeaderNameCrossOriginOpenerPolicy = "Cross-Origin-Opener-Policy"
	HeaderNameCrossOriginEmbedPolicy  = "Cross-Origin-Embedder-Policy"
	HeaderNameCrossOriginResourcePol  = "Cross-Origin-Resource-Policy"
	HeaderNameXDNSPrefetchControl     = "X-DNS-Prefetch-Control"
	HeaderNameXDownloadOptions        = "X-Download-Options"
	HeaderNameXPermittedCrossDomain   = "X-Permitted-Cross-Domain-Policies"

	// Rate limiting.
	HeaderNameRetryAfter       = "Retry-After"
	HeaderNameXRateLimitLimit  = "X-RateLimit-Limit"
	HeaderNameXRateLimitRemain = "X-RateLimit-Remaining"
	HeaderNameXRateLimitReset  = "X-RateLimit-Reset"

	// Response metadata.
	HeaderNameLocation = "Location"
	HeaderNameAllow    = "Allow"
	HeaderNameServer   = "Server"
	HeaderNameDate     = "Date"

	// WebSocket.
	HeaderNameSecWebSocketKey       = "Sec-WebSocket-Key"
	HeaderNameSecWebSocketVersion   = "Sec-WebSocket-Version"
	HeaderNameSecWebSocketProtocol  = "Sec-WebSocket-Protocol"
	HeaderNameSecWebSocketExtension = "Sec-WebSocket-Extensions"
	HeaderNameSecWebSocketAccept    = "Sec-WebSocket-Accept"

	// Misc.
	HeaderNameXPoweredBy = "X-Powered-By"
	HeaderNameDNT        = "DNT"
	HeaderNameExpect     = "Expect"
	HeaderNameFrom       = "From"
	HeaderNameRange      = "Range"
	HeaderNameWarning    = "Warning"
)
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 FuckSecurity added in v1.5.0

func FuckSecurity()

FuckSecurity enables permissive defaults for quick local development. CORS allows all origins, WebSocket accepts any origin, etc. Call UnfuckSecurity() to restore secure defaults.

func GetClientIP

func GetClientIP(r *http.Request) string

func GetDefaultCORSAllowAllOrigins added in v1.5.0

func GetDefaultCORSAllowAllOrigins() bool

GetDefaultCORSAllowAllOrigins returns whether CORS should allow all origins. Secure default: false. Dev mode: true.

func GetDefaultCORSAllowHeaders

func GetDefaultCORSAllowHeaders() string

func GetDefaultCORSAllowMethods

func GetDefaultCORSAllowMethods() string

func GetDefaultWebSocketCheckOrigin

func GetDefaultWebSocketCheckOrigin(r *http.Request) bool

GetDefaultWebSocketCheckOrigin returns the default origin checker for WebSocket connections. Secure default: validates Origin matches request Host. Dev mode: allows all origins.

func GetPermissiveWebSocketCheckOrigin added in v1.5.0

func GetPermissiveWebSocketCheckOrigin(_ *http.Request) bool

GetPermissiveWebSocketCheckOrigin always allows all origins. Use with WithUpgradeHandlerCheckOrigin when you need to bypass origin validation for a specific handler without enabling global dev mode.

func GetRequestID

func GetRequestID(r *http.Request) string

func IsDevMode added in v1.5.0

func IsDevMode() bool

IsDevMode returns true if FuckSecurity was called.

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 UnfuckSecurity added in v1.5.0

func UnfuckSecurity()

UnfuckSecurity restores secure defaults after FuckSecurity.

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