Documentation
¶
Index ¶
- Constants
- Variables
- func CleanRoute(RoutePath string) string
- func GetAllVersions() []string
- func GetAllowedMethods(version string) string
- func GetCLFTime() string
- func GetHighestVersion(requestVersion string) string
- func GetResponseVersion(requestVersion string) string
- func GetRfc1123Time() string
- func GetServerDefaults(key string) any
- func IsHttpDate(value string) (bool, time.Time)
- func IsMethodAllowed(version string, requestMethod string) bool
- func NormalizeRoute(RoutePath string) []string
- type ConnectionWatcher
- type CustomError
- type File
- type FileSystem
- type FileSystemError
- type Headers
- type HttpRequest
- type HttpResponse
- func (res *HttpResponse) AddHeader(HeaderKey string, HeaderValue string)
- func (res *HttpResponse) Initialize(version string, writer io.Writer)
- func (res *HttpResponse) Send(content string) error
- func (res *HttpResponse) SendError(Content string) error
- func (res *HttpResponse) SendFile(CompleteFilePath string, OnlyMetadata bool) error
- func (res *HttpResponse) SetServer(serverRef *HttpServer)
- func (res *HttpResponse) Status(status StatusCode)
- func (res *HttpResponse) Write() error
- type HttpServer
- func (srv *HttpServer) Listen()
- func (srv *HttpServer) Log(message string, level string)
- func (srv *HttpServer) NewRequest(Connection net.Conn) *HttpRequest
- func (srv *HttpServer) NewResponse(Connection net.Conn, request *HttpRequest) *HttpResponse
- func (srv *HttpServer) SetLogger(logFormat string)
- func (srv *HttpServer) Use(middleware Middleware)
- type HttpStatus
- type MatchInfo
- type Middleware
- type Middlewares
- type Params
- type PrefixTree
- type PrefixTreeNode
- type ReadTimeoutError
- type RequestParseError
- type ResponseError
- type Route
- type RouteHandler
- type Router
- func (rtr *Router) Connect(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Delete(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Get(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Head(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Match(request *HttpRequest) (*Route, error)
- func (rtr *Router) Options(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Post(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Put(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- func (rtr *Router) Static(RoutePath string, TargetPath string) error
- func (rtr *Router) Trace(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
- type RoutingError
- type StatusCode
- type StopFunction
Constants ¶
const ( ERROR_MSG_CONTENT_TYPE = "text/html" HEADER_LINE_SEPERATOR = "\r\n" REQUEST_LINE_SEPERATOR = " " HEADER_KEY_VALUE_SEPERATOR = ":" ROUTE_SEPERATOR = "/" // Informational data logged to the terminal. INFO_LEVEL = "INFO" // Error data logged to the terminal. ERROR_LEVEL = "ERROR" // Warning(s) logged to the terminal. WARN_LEVEL = "WARNING" // This is the default format in which request status is logged to the terminal. // This follows the common Apache log format which is as follows: // // :remote-addr [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] COMMON_LOGGER = "common" // Concise output colored by response status for development use. // The :status token will be colored green for success codes, red for server error codes, yellow for client error codes, cyan for redirection codes, and uncolored for information codes. // // :method :url :status :response-time ms - :res[content-length] DEV_LOGGER = "dev" // The minimal output. // // :method :url :status :res[content-length] - :response-time ms TINY_LOGGER = "tiny" // Shorter than default, also including response time. // // :remote-addr :method :url HTTP/:http-version :status :res[content-length] - :response-time ms SHORT_LOGGER = "short" )
const (
// Size in bytes for each chunk of data being read from a file.
CHUNK_SIZE = 1024
)
Variables ¶
var AllowedContentTypes map[string]string
List of content types supported by the web server.
var DateHeaders []string
Collection of headers supported by the server that has a date value.
var ErrorHandler = func(request *HttpRequest, response *HttpResponse) { if response.StatusCode < int(Status400) { request.Server.Log("Response Status code should be 400 or above to invoke the default error handler", ERROR_LEVEL) return } if response.StatusCode == int(Status405) { response.Headers.Add("Allow", GetAllowedMethods(response.Version)) } statusCode := StatusCode(response.StatusCode) err := response.SendError(statusCode.GetErrorContent()) if err != nil { request.Server.Log(err.Error(), ERROR_LEVEL) } }
Default error handler logic to be implemented for sending an error response back to client.
var ResponseStatusCodes []HttpStatus
List of response status codes and their associated information.
var ServerDefaults map[string]any
A map containing all the default server configuration values.
var StaticFileHandler = func(request *HttpRequest, response *HttpResponse) { targetFilePath, ok := request.Locals["StaticFilePath"].(string) if !ok { request.Server.Log("Static file path not available in the request instance", ERROR_LEVEL) return } targetFilePath = strings.TrimSpace(targetFilePath) isCondGet, err := request.IsConditionalGet(targetFilePath) if err != nil { request.Server.Log(err.Error(), ERROR_LEVEL) } if !isCondGet { response.Status(Status200) err := response.SendFile(targetFilePath, false) if err != nil { request.Server.Log(err.Error(), ERROR_LEVEL) } } else { response.Status(Status304) err := response.SendFile(targetFilePath, true) if err != nil { request.Server.Log(err.Error(), ERROR_LEVEL) } } }
Handler to fetch static file and send the file contents as response back to the client.
var TextColor = textColor{}
Global instance to apply colors to text printed on ANSI supported terminals.
var Versions map[string][]string
List of all versions of HTTP supported by the web server and the HTTP methods supported for each version.
Functions ¶
func CleanRoute ¶
Removes all but one leading '/' and all the trailing '/' from the given route path and returns the cleaned value. Replaces all instances of "//" with "/". This function is used for cleaning URL route paths. If the given route path is an empty string, it is returned as-is.
func GetAllVersions ¶
func GetAllVersions() []string
Gets an array of all the versions of HTTP supported by the web server.
func GetAllowedMethods ¶
Gets the list of allowed HTTP methods supported by the web server for the given HTTP version.
func GetHighestVersion ¶
Gets the highest version of HTTP supported by the web server that is compatible with the given request version.
func GetResponseVersion ¶
Returns the HTTP response version for the given request version value.
func GetServerDefaults ¶
Returns the value for the given key from server default configuration values.
func IsHttpDate ¶
Checks if the given date time value corresponds to a valid HTTP date and returns two values. First returned is a boolean value which indicates if the given date value conforms to a valid format. Second returned is a time.Time value corresponding to the given string and if its invalid, returns the zero time.
func IsMethodAllowed ¶
Checks if the given HTTP method is supported by the web server for the given version.
func NormalizeRoute ¶
Normalizes the given route path into a slice of route parts present in the path. This function also removes any leading or trailing space and '/' before getting the route parts.
Types ¶
type ConnectionWatcher ¶
type ConnectionWatcher struct {
// contains filtered or unexported fields
}
Structure to track all the active connections maintained by the server.
func (*ConnectionWatcher) GetCount ¶
func (cw *ConnectionWatcher) GetCount() int
GetCount returns the current number of active connections. Thread-safe method providing read-only access to connection count. Returns the number of concurrent client connections to the server.
func (*ConnectionWatcher) UpdateCount ¶
func (cw *ConnectionWatcher) UpdateCount(delta int)
UpdateCount increases the connection count by the specified delta. Used internally to track active connections in a thread-safe manner. Positive delta adds connections, negative delta removes connections.
type CustomError ¶
type CustomError struct {
// The actual error message raised by the program.
Message string
}
Custom error to track errors raised between receiving the request and sending the response.
func (*CustomError) Error ¶
func (ce *CustomError) Error() string
Returns a customized error message associated with the instance of RequestResponseError.
type File ¶
type File struct {
// Base name of the file.
Name string
// Complete Path of the file in the local file system.
Path string
// contains filtered or unexported fields
}
Structure to represent a file in the local file system.
func (*File) Contents ¶
Contents reads and returns complete file content as byte slice with chunked processing. Use for static file serving, template loading, file uploads, and binary content handling. Opens file, reads in configurable chunks, assembles complete content, closes handle automatically. Parameters: No parameters (uses file.Path). Returns: []byte (complete file content), error (FileSystemError if reading fails).
func (*File) Extension ¶
Extension extracts file extension in normalized lowercase format without leading period. Use for MIME type detection, file validation, routing decisions, and security checks. Removes period, converts to lowercase, trims whitespace for consistent comparison. Parameters: No parameters (uses file.Path). Returns: string (normalized file extension like "pdf", "html", empty string if no extension).
func (*File) LastModified ¶
LastModified returns file modification timestamp from filesystem metadata for caching support. Use for Last-Modified headers, conditional GET requests, cache invalidation, and file monitoring. Retrieved from os.FileInfo, returns zero time if file doesn't exist, suitable for HTTP headers. Parameters: No parameters (uses file.stats). Returns: time.Time (file modification timestamp, zero time if file doesn't exist).
Note: Modification time precision and behavior may vary between different filesystems and operating systems.
func (*File) MediaType ¶
MediaType determines MIME type for file based on extension for proper HTTP Content-Type headers. Use for static file serving, file uploads, API responses, and browser rendering control. Looks up extension in internal registry, supports web/document/multimedia types, fallback to default. Parameters: No parameters (uses file extension). Returns: string (MIME type like "text/html", "image/png", "application/pdf").
Note: MIME type detection is based solely on file extension. For security-sensitive applications, consider additional content validation beyond extension-based detection.
func (*File) Size ¶
Size returns file size in bytes from filesystem metadata without reading content. Use for Content-Length headers, upload validation, bandwidth estimation, and quota management. Retrieved from os.FileInfo statistics, efficient for large files, accurate for all file types. Parameters: No parameters (uses file.stats). Returns: int64 (file size in bytes, 0 if file doesn't exist or stats unavailable).
type FileSystem ¶
type FileSystem struct{}
Structure to connect to the local file system and access files/folders.
func (*FileSystem) CleanPath ¶
func (fs *FileSystem) CleanPath(Path string) string
CleanPath normalizes filesystem paths by removing redundant elements and standardizing separators. Use for security (prevents path traversal), consistency, and cross-platform compatibility. Removes redundant separators, resolves . and .. references, trims whitespace automatically. Parameter: Path (raw filesystem path that may contain redundant elements). Returns: string (cleaned and normalized path suitable for filesystem operations).
func (*FileSystem) Exists ¶
func (fs *FileSystem) Exists(CompletePath string) bool
Exists checks whether file or directory exists at specified path with reliable validation. Use for file upload conflict detection, configuration presence checking, and asset validation. Cleans path, uses lightweight os.Stat() operation, works with all filesystem entity types. Parameter: CompletePath (path to check, cleaned automatically). Returns: bool (true if path exists and accessible, false otherwise).
func (*FileSystem) GetFile ¶
func (fs *FileSystem) GetFile(CompleteFilePath string) (*File, error)
GetFile creates File instance with metadata for specified path with validation and normalization. Use for static file serving, file access validation, and metadata extraction operations. Verifies existence, ensures regular file (not directory), extracts metadata, cleans path. Parameter: CompleteFilePath (absolute or relative path to target file). Returns: *File (instance with metadata and methods), error (FileSystemError if access fails).
func (*FileSystem) IsAbsolute ¶
func (fs *FileSystem) IsAbsolute(CompleteFilePath string) bool
IsAbsolute determines whether provided path is absolute filesystem path for security validation. Use for path validation, security checks, configuration verification, and preventing traversal attacks. Checks Unix ("/path") and Windows ("C:\path", "\\server\share") absolute path formats. Parameter: CompleteFilePath (path string to validate, cleaned automatically). Returns: bool (true if path is absolute, false if relative).
func (*FileSystem) IsDirectory ¶
func (fs *FileSystem) IsDirectory(CompletePath string) bool
IsDirectory determines whether specified path points to accessible directory with safe error handling. Use for static file path validation, upload directory verification, and configuration checks. Cleans path, retrieves filesystem stats, returns false for non-existent/inaccessible paths. Parameter: CompletePath (path to validate, cleaned automatically). Returns: bool (true if path is accessible directory, false otherwise).
type FileSystemError ¶
type FileSystemError struct {
// The target file path that is causing the error.
TargetPath string
// The actual error message raised by the program.
Message string
}
A custom error to track file system related errors raised.
func (*FileSystemError) Error ¶
func (fsf *FileSystemError) Error() string
Returns a customized error message associated with the instance of FileSystemError.
type Headers ¶
Represents a collection of headers (request or response).
func (Headers) Add ¶
Add inserts header key-value pair with automatic MIME key normalization and multi-value support. Use to add HTTP headers like Content-Type, Set-Cookie, or Accept with proper formatting. Normalizes keys to canonical format, splits comma-separated values, appends to existing headers. Parameters: key (header name), value (header value, comma-separated values split automatically). Returns: No return value, header stored in collection for HTTP transmission.
func (Headers) Get ¶
Get retrieves header value for specified key with case-insensitive lookup and multi-value joining. Use to check for Content-Type, Authorization, or any header with automatic key normalization. Joins multiple values with commas, normalizes key to canonical MIME format automatically. Parameter: key (header name, case-insensitive). Returns: string (combined header value), bool (true if header exists, false otherwise).
func (Headers) Length ¶
Length returns total number of unique header keys in the headers collection. Use for validation, debugging, logging header collection size, and implementing header limits. Counts unique header keys only, not individual values (multi-value headers count as one). Parameters: No parameters. Returns: int (number of unique header keys in collection).
type HttpRequest ¶
type HttpRequest struct {
// HTTP request method like GET, POST, PUT etc.
Method string
// Resource path requested by the client.
ResourcePath string
// HTTP version that the request complies with. It is of format <major>.<minor> which refers to the major and minor versions respectively.
Version string
// Collection of all the request headers received.
Headers Headers
// Represents the complete contents of the request body as a stream of bytes.
BodyBytes []byte
// key-value pairs to hold variables available during the entire request lifecycle.
Locals map[string]any
// Collection of all query parameters stored as key-values pair.
Query Params
// Collection of all path parameter values stored as key-value pair.
Segments Params
// The IP address and port number of the client who made the request to the server
ClientAddress string
// The server instance processing this request.
Server *HttpServer
// The actual content contained by the request. The type of the data is determined at run time depending on the data sent as part of the request.
Body any
// contains filtered or unexported fields
}
Structure to represent a HTTP request received by the web server.
func (*HttpRequest) AddHeader ¶
func (req *HttpRequest) AddHeader(HeaderKey string, HeaderValue string)
AddHeader adds a header key-value pair with key normalization and validation. Normalizes keys to canonical MIME format and validates date header formats. Logs errors for invalid date formats but continues processing. Used during request parsing to build header collection.
func (*HttpRequest) Initialize ¶
func (req *HttpRequest) Initialize(reader io.Reader)
Initialize sets up HttpRequest with default values for reading HTTP data. Creates empty collections, sets HTTP version to "0.9", initializes locals map. Called internally during request creation from network connections. Prepares request for parsing headers, body, and parameters using Read().
func (*HttpRequest) IsConditionalGet ¶
func (req *HttpRequest) IsConditionalGet(CompleteFilePath string) (bool, error)
IsConditionalGet checks if this is a conditional GET request with "If-Modified-Since" header. Compares file's modification time with the header date for caching optimization. Returns true if file unchanged (send 304), false if file should be sent (200). Used for bandwidth-efficient static file serving with proper cache validation.
func (*HttpRequest) ProcessingTime ¶
func (req *HttpRequest) ProcessingTime() int64
ProcessingTime calculates time elapsed since request processing began in milliseconds. Uses "Started" timestamp from req.Locals to measure elapsed time. Used for performance monitoring, logging, and timeout detection. Returns 0 if start time is unavailable or not set.
func (*HttpRequest) Read ¶
func (req *HttpRequest) Read() error
Read parses complete HTTP request from network stream into HttpRequest fields. Parses request line, headers, query parameters, and body (if Content-Length present). Handles HTTP/0.9, 1.0, and 1.1 formats with error handling for malformed requests. Returns RequestParseError on parsing failures, nil on success.
type HttpResponse ¶
type HttpResponse struct {
// Status code of the response being sent back to the client like 200, 203, 404 etc.
StatusCode int
// Status message associated with the response status code.
StatusMessage string
// HTTP version of the response being sent back.
Version string
// Collection of all response headers being sent by the server.
Headers Headers
// Complete contents of the response body as a stream of bytes.
BodyBytes []byte
// The server instance processing this response.
Server *HttpServer
// key-value pairs to hold variables available during the entire response lifecycle.
Locals map[string]any
// contains filtered or unexported fields
}
Structure to represent a HTTP response sent back by the server to the client.
func (*HttpResponse) AddHeader ¶
func (res *HttpResponse) AddHeader(HeaderKey string, HeaderValue string)
AddHeader adds a header key-value pair to response headers with validation and normalization. Use to set HTTP headers like Content-Type, Cache-Control, or custom headers before sending. Normalizes keys to canonical format, validates date headers, supports multiple values per key. Parameters: HeaderKey (header name), HeaderValue (header value). Returns: No return value, headers stored in response Headers collection.
Common response headers:
- Content-Type, Content-Length, Content-Encoding
- Cache-Control, Expires, ETag, Last-Modified
- Location (for redirects), Set-Cookie
- Access-Control-* (for CORS)
func (*HttpResponse) Initialize ¶
func (res *HttpResponse) Initialize(version string, writer io.Writer)
Initialize sets up an HttpResponse instance with default values and prepares it for HTTP output. Use for creating new response instances with proper HTTP version handling. Sets HTTP version (defaults to "0.9"), creates header/locals collections, adds standard headers. Parameters: version (HTTP version), writer (output destination). Returns: Configured response ready for sending data.
func (*HttpResponse) Send ¶
func (res *HttpResponse) Send(content string) error
Send transmits string content as HTTP response body with automatic headers. Use to send text, JSON, HTML, or other string-based content to clients. Sets Content-Length automatically and uses default Content-Type if not specified. Parameter: content (string data to send as response body). Returns: error on transmission failure, nil on successful response.
func (*HttpResponse) SendError ¶
func (res *HttpResponse) SendError(Content string) error
SendError transmits error content as HTTP response with proper error headers and content type. Use to send error messages, HTML error pages, or JSON error responses to clients. Sets appropriate Content-Type and Content-Length headers automatically. Parameter: Content (error message or formatted content to send). Returns: error on transmission failure, nil on successful error response.
func (*HttpResponse) SendFile ¶
func (res *HttpResponse) SendFile(CompleteFilePath string, OnlyMetadata bool) error
SendFile transmits a file from filesystem as HTTP response with automatic headers and MIME detection. Use to serve static files, downloads, or handle HEAD requests for file metadata. Sets Content-Length, Last-Modified, and Content-Type headers automatically. Parameters: CompleteFilePath (absolute path), OnlyMetadata (true for HEAD requests). Returns: error on file access/transmission failure, nil on success.
func (*HttpResponse) SetServer ¶
func (res *HttpResponse) SetServer(serverRef *HttpServer)
Sets the server field to the given server instance reference.
func (*HttpResponse) Status ¶
func (res *HttpResponse) Status(status StatusCode)
Status sets the HTTP status code and message for this response. Use to set response status before sending content (200 OK, 404 Not Found, 500 Error, etc.). Configures both numeric code and text message for proper HTTP response line. Parameter: status (StatusCode constant like Status200, Status404, Status500). Returns: No return value, status stored in response for transmission.
func (*HttpResponse) Write ¶
func (res *HttpResponse) Write() error
Write transmits the complete HTTP response (status, headers, body) to the client connection. Use to send finalized response data to network writer with proper HTTP formatting. Handles HTTP/0.9 (body only) and HTTP/1.0+ (full response) versions automatically. Called internally by Send(), SendFile(), and SendError() methods. Returns: error if transmission fails, nil on successful write and flush.
type HttpServer ¶
type HttpServer struct {
// Hostname of the web server instance.
HostAddress string
// Port number where web server instance is listening for incoming requests.
PortNumber int
// // key-value pairs to hold variables available for all requests and responses processed by the server instance.
Locals map[string]any
// Router instance that contains all the routes and their associated handlers.
Router *Router
// contains filtered or unexported fields
}
Structure to create an instance of a web server.
func NewServer ¶
func NewServer(HostAddress string, PortNumber int) *HttpServer
Creates a new instance of HTTP web server and binds it to the given hostname and port number. If the hostname is empty, the web server instance is bound to the locahost. If the port number is zero, the web server instance is bound to port - 8080.
func (*HttpServer) Listen ¶
func (srv *HttpServer) Listen()
Listen starts the HTTP server and begins accepting connections. Blocks until terminated by interrupt signal (Ctrl+C, SIGINT, SIGTERM). Creates TCP listener, handles graceful shutdown, and manages connections. Ensure HostAddress, PortNumber, and Router are configured before calling.
func (*HttpServer) Log ¶
func (srv *HttpServer) Log(message string, level string)
Log outputs a message to the server's log stream with specified log level. Supports INFO_LEVEL, WARN_LEVEL (yellow), and ERROR_LEVEL (red) with colors. Includes timestamp, server name, log level, and message in output. Thread-safe method used for operational logging by server and applications.
func (*HttpServer) NewRequest ¶
func (srv *HttpServer) NewRequest(Connection net.Conn) *HttpRequest
NewRequest creates and initializes a new HttpRequest for the given connection. Sets up request with default values, client address, and server reference. Called internally by the server for each incoming connection. Returns pointer to the initialized HttpRequest instance.
func (*HttpServer) NewResponse ¶
func (srv *HttpServer) NewResponse(Connection net.Conn, request *HttpRequest) *HttpResponse
NewResponse creates and initializes a new HttpResponse for the given connection. Sets up response with appropriate HTTP version, default headers, and server reference. Called internally by the server for each request. Returns pointer to the initialized HttpResponse instance.
func (*HttpServer) SetLogger ¶
func (srv *HttpServer) SetLogger(logFormat string)
SetLogger configures the logging format for HTTP request processing logs. Supports COMMON_LOGGER, DEV_LOGGER, TINY_LOGGER, and SHORT_LOGGER formats. Defaults to COMMON_LOGGER if an unsupported format is provided. Use to customize how requests and responses are logged to console.
func (*HttpServer) Use ¶
func (srv *HttpServer) Use(middleware Middleware)
Use registers a middleware function to execute for all incoming HTTP requests. Server-level middleware runs before route-specific middleware and handlers. Middleware functions execute in the order they were registered. Use for authentication, logging, body parsing, CORS, etc.
type HttpStatus ¶
type HttpStatus struct {
// HTTP response status code.
Code StatusCode
// Short message for the corresponding status code.
Message string
// Error description for error status codes (>=400).
ErrorDescription string
}
Structure to represent a response status code and its associated information.
type MatchInfo ¶
type MatchInfo struct {
// List of all path parameter(s) fetched by comparing the given route with the one matched in the prefix tree.
Segments Params
// The matched route in the prefix tree.
MatchedPath string
// Route instance associated with the given path.
MatchedRoutes []*Route
}
Contains the match information when a given route is matched with the prefix tree.
func (*MatchInfo) AddToRoutes ¶
Adds a route instance to the routes list of the MatchInfo instance
type Middleware ¶
type Middleware func(*HttpRequest, *HttpResponse, StopFunction)
A function to execute operations like validations and transformations before before performing the backend tasks.
func JsonParser ¶
func JsonParser() Middleware
Returns a middleware function that checks for requests with JSON payloads and parses them from source byte stream. If the request payload contains a JSON object, the request body will contain the parsed value as map[string]any instance. If the request payload contains a JSON array, the request body will contain the parsed value as []any{ map[string]any } instance.
func UrlEncoded ¶
func UrlEncoded() Middleware
Returns a middleware function that checks for request payloads of type "application/x-www-form-urlencoded" and fetches the parsed values. The parsed values are stored in an instance of type - map[string][]string.
type Middlewares ¶
type Middlewares struct {
// Flag to denote if the next middleware in the stack will be executed.
// the default value for this flag is true.
// At the end of execution of each middleware this flag can be updated by using the "StopFunction" to end the execution of request with that middleware.
ProcessNext bool
// List of all middlewares to be processed as part of the stack for the associated instance.
Stack []Middleware
}
Structure to hold and process one or more middlewares. Middlewares are executed in the order in which they were defined. They can either be associated with a route or to a server instance. Miidlewares associated with a server instance are applicable to all requests directed to the server instance.
func CreateMiddlewares ¶
func CreateMiddlewares(middlewareList ...Middleware) *Middlewares
Create a new instance of "Middlewares" and return a reference to the instance.
func (*Middlewares) Stop ¶
func (mds *Middlewares) Stop()
Stops further execution of middlewares in the stack by marking the "ProcessNext" flag as false.
type Params ¶
Collection of all parameters in a URL. The params can either be query parameters or path parameters.
func (Params) Add ¶
Add inserts or appends parameter values to params collection with multi-value support. Use for URL parsing, route matching, form processing, and middleware parameter injection. Creates new entry for new keys, appends to existing keys, preserves value order. Parameters: key (parameter name, whitespace trimmed), paramValues (slice of values to add). Returns: No return value, values stored in collection for retrieval via Get().
func (Params) Get ¶
Get retrieves all values for specified parameter key from query and path parameters. Use to access route path parameters (:id), query parameters (?name=value), and multi-value parameters. Trims whitespace from key, preserves value order, handles both single and multiple values. Parameter: key (parameter name to lookup like "id", "name", "category"). Returns: []string (slice of all values for parameter), bool (true if parameter exists).
func (Params) Length ¶
Length returns total number of unique parameter keys in the collection. Use for request validation, debugging, parameter limits, and monitoring request complexity. Counts unique parameter names only, not individual values (multi-value params count as one). Parameters: No parameters. Returns: int (number of unique parameter keys in collection).
type PrefixTree ¶
type PrefixTree struct {
// Root node of the prefix tree
Root *PrefixTreeNode
}
Structure to represent the prefix tree to be built
func EmptyPrefixTree ¶
func EmptyPrefixTree() *PrefixTree
Creates an empty prefix tree and returns a pointer to the root node of the tree. An empty prefix tree contains only the root node with an empty string assigned as its value.
func (*PrefixTree) GetAllRoutes ¶
func (pt *PrefixTree) GetAllRoutes() []string
Get all the routes available in the prefix tree.
func (*PrefixTree) Insert ¶
func (pt *PrefixTree) Insert(RoutePath string, MappedRoute *Route)
Inserts the given route path to the prefix tree.
func (*PrefixTree) Match ¶
func (pt *PrefixTree) Match(RoutePath string) *MatchInfo
Find a match for the given route in the prefix tree.
type PrefixTreeNode ¶
type PrefixTreeNode struct {
// Child elements to the current node stored as a map.
Children map[string]*PrefixTreeNode
// Route instance mapped to the current node. Default value is nil.
Routes []*Route
}
Structure to represent each individual node of the prefix tree (trie tree).
func NewPrefixTreeNode ¶
func NewPrefixTreeNode() *PrefixTreeNode
Creates and returns pointer to a new node in the prefix tree.
func (*PrefixTreeNode) AddToRoutes ¶
func (ptn *PrefixTreeNode) AddToRoutes(route *Route)
Adds a route instance to the routes list of the prefix tree node.
type ReadTimeoutError ¶
type ReadTimeoutError struct{}
Custom error to track read timeout errors raised on incoming TCP Connections
func (*ReadTimeoutError) Error ¶
func (rte *ReadTimeoutError) Error() string
Error message associated with the read timeout error raised for the underlying TCP connection.
type RequestParseError ¶
type RequestParseError struct {
// Refers to the part of the request which while being parsed raised the error - Header, Body, QueryParams are the possible values.
Section string
// The invalid value that caused the error.
Value string
// Refers to the actual error message raised.
Message string
}
Custom error to track errors raised when a HTTP request received is being read and parsed.
func (*RequestParseError) Error ¶
func (rpe *RequestParseError) Error() string
Returns the error message associated with the instance of RequestParseError.
type ResponseError ¶
type ResponseError struct {
// Refers to the part of the request which while being parsed raised the error - Header, Body, RespWrite, StatusLine are the possible values.
Section string
// The invalid value that caused the error.
Value string
// Refers to the actual error message raised.
Message string
}
Custom error to track errors raised when a HTTP response message is being formed
func (ResponseError) Error ¶
func (resErr ResponseError) Error() string
Returns the error message associated with the instance of RequestParseError.
type Route ¶
type Route struct {
// Handler function to be executed for the route paths.
RouteHandler RouteHandler
// HTTP method for which the route is defined
Method string
// List of all route level middlewares configured.
Middlewares []Middleware
}
Structure to contain information about a single route declared in the Router.
type RouteHandler ¶
type RouteHandler func(*HttpRequest, *HttpResponse)
Represents a handler function that is executed once any received request is parsed. You can define different handlers for different routes and HTTP methods.
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Structure to hold all the routes and the associated routing logic.
func NewRouter ¶
func NewRouter() *Router
Creates a new instance of Router and returns a reference to the instance.
func (*Router) Connect ¶
func (rtr *Router) Connect(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Connect registers HTTP CONNECT endpoint for establishing tunnels through proxy servers. Use for proxy connections, SSL tunneling, and WebSocket upgrade handling. Typically used by proxy servers and clients requiring secure tunnel establishment. Parameters: RoutePath (URL pattern), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Delete ¶
func (rtr *Router) Delete(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Delete registers HTTP DELETE endpoint for removing resources permanently with idempotent behavior. Use for resource deletion, cleanup operations, session logout, and administrative management. Returns 204 No Content on success, handles non-existent resources gracefully. Parameters: RoutePath (URL pattern with ID), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Get ¶
func (rtr *Router) Get(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Get registers HTTP GET endpoint with handler and optional middleware for data retrieval. Use for web pages, API endpoints, content serving with static/dynamic path support. Supports path parameters (:id), wildcards (*), and middleware chain execution. Parameters: RoutePath (URL pattern), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Head ¶
func (rtr *Router) Head(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Head registers HTTP HEAD endpoint for retrieving headers without body content. Use for resource validation, metadata checking, and bandwidth-efficient probing. Returns same headers as GET but no response body for efficient resource validation. Parameters: RoutePath (URL pattern), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Match ¶
func (rtr *Router) Match(request *HttpRequest) (*Route, error)
Match finds route handler for HTTP request by searching static files and dynamic patterns. Use internally by server to locate appropriate handler for incoming requests. Checks static routes first (GET/HEAD), then dynamic patterns with parameter extraction. Parameter: request (HttpRequest with path and method to match). Returns: *Route with handler and middleware, error if no match found.
func (*Router) Options ¶
func (rtr *Router) Options(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Options registers HTTP OPTIONS endpoint for CORS preflight requests and method discovery. Use for cross-origin API access, capability discovery, and browser preflight handling. Sets CORS headers (Allow-Origin, Allow-Methods, Allow-Headers) for secure cross-origin requests. Parameters: RoutePath (URL pattern), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Post ¶
func (rtr *Router) Post(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Post registers HTTP POST endpoint for creating resources and processing form/JSON data. Use for user creation, form submissions, file uploads, and API operations that modify state. Supports body parsing middleware (JsonParser, UrlEncoded) for request data processing. Parameters: RoutePath (URL pattern), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Put ¶
func (rtr *Router) Put(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Put registers HTTP PUT endpoint for updating/replacing resources with idempotent operations. Use for complete resource updates, configuration changes, and file uploads to specific URLs. Idempotent behavior (safe to repeat), client specifies resource location unlike POST. Parameters: RoutePath (URL pattern with ID), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
func (*Router) Static ¶
Static registers a route to serve static files from specified filesystem directory. Use to serve CSS, JS, images, and other assets with automatic MIME detection and caching. Maps URL prefix to filesystem path with security validation and directory traversal protection. Parameters: RoutePath (URL prefix), TargetPath (absolute filesystem directory). Returns: error if target path invalid or inaccessible, nil on successful registration.
func (*Router) Trace ¶
func (rtr *Router) Trace(RoutePath string, handlerFunc RouteHandler, middlewareList ...Middleware) error
Trace registers HTTP TRACE endpoint for diagnostic loopback testing and request tracing. Use for debugging HTTP request path, proxy behavior, and network diagnostics. Echoes received request headers back to client for troubleshooting purposes. Parameters: RoutePath (URL pattern), handlerFunc (route handler), middlewareList (optional middleware). Returns: error if route registration fails, nil on successful registration.
type RoutingError ¶
type RoutingError struct {
// The target route path which has caused the issue.
RoutePath string
// The actual error message raised
Message string
}
Custom error to track errors raised by the router associated with the web server.
func (*RoutingError) Error ¶
func (re *RoutingError) Error() string
Returns the error message associated with the RoutingError instance.
type StatusCode ¶
type StatusCode int
const ( Status100 StatusCode = 100 Status101 StatusCode = 101 Status102 StatusCode = 102 Status103 StatusCode = 103 Status200 StatusCode = 200 Status201 StatusCode = 201 Status202 StatusCode = 202 Status203 StatusCode = 203 Status204 StatusCode = 204 Status205 StatusCode = 205 Status206 StatusCode = 206 Status207 StatusCode = 300 Status208 StatusCode = 208 Status300 StatusCode = 300 Status301 StatusCode = 301 Status302 StatusCode = 302 Status303 StatusCode = 303 Status304 StatusCode = 304 Status305 StatusCode = 305 Status307 StatusCode = 307 Status308 StatusCode = 308 Status400 StatusCode = 400 Status401 StatusCode = 401 Status402 StatusCode = 402 Status403 StatusCode = 403 Status404 StatusCode = 404 Status405 StatusCode = 405 Status406 StatusCode = 406 Status407 StatusCode = 407 Status408 StatusCode = 408 Status409 StatusCode = 409 Status410 StatusCode = 410 Status411 StatusCode = 411 Status412 StatusCode = 412 Status413 StatusCode = 413 Status414 StatusCode = 414 Status415 StatusCode = 415 Status416 StatusCode = 416 Status417 StatusCode = 417 Status421 StatusCode = 421 Status422 StatusCode = 422 Status423 StatusCode = 423 Status424 StatusCode = 424 Status425 StatusCode = 425 Status426 StatusCode = 426 Status428 StatusCode = 428 Status429 StatusCode = 429 Status431 StatusCode = 431 Status500 StatusCode = 500 Status501 StatusCode = 501 Status502 StatusCode = 502 Status503 StatusCode = 503 Status504 StatusCode = 504 Status505 StatusCode = 505 Status506 StatusCode = 506 Status507 StatusCode = 507 Status508 StatusCode = 508 Status511 StatusCode = 511 )
func (StatusCode) GetErrorContent ¶
func (code StatusCode) GetErrorContent() string
GetErrorContent generates a default HTML error page for HTTP error status codes. Used when custom error handling is not implemented to provide standardized error pages. Creates complete HTML document with status code, reason phrase, and error description. Returns empty string if status code is not found in the registry.
func (StatusCode) GetStatusMessage ¶
func (code StatusCode) GetStatusMessage() string
GetStatusMessage retrieves the standard HTTP reason phrase for this status code. Used internally by the response system to construct HTTP status lines like "HTTP/1.1 200 OK". Returns the official reason phrase (e.g., "OK", "Not Found") for standard status codes. Returns empty string for unrecognized status codes.
type StopFunction ¶
type StopFunction func()
Function used to update if subsequent middlewares in the stack have to be processed before a response can be sent back to the client.