Module: Perfect-HTTP
enum HTTPFilterPriority
Execution priority for request filters.
case low
Lowest priority. Run last.
case medium
Medium priority.
case high
Highest priority. Run first.
enum HTTPRequestFilterResult
Result from one filter.
case halt(HTTPRequest, HTTPResponse)
Halt and finalize the request. Handler is not run.
case execute(HTTPRequest, HTTPResponse)
Stop filtering and execute the request.
No other filters at the current priority level will be executed.
enum HTTPResponseFilterResult
Response from one filter.
case `continue`
Continue with filtering.
case done
Stop executing filters until the next push.
case halt
Halt and close the request.
protocol HTTPRequestFilter
A filter which can be called to modify a HTTPRequest.
func filter(request: HTTPRequest, response: HTTPResponse, callback: (HTTPRequestFilterResult) -> ())
Called once after the request has been read but before any handler is executed.
protocol HTTPResponseFilter
A filter which can be called to modify a HTTPResponse.
func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ())
Called zero or more times for each bit of body data which is sent to the client.
enum HTTPRequestHeader
An HTTP request header.
enum Name: Hashable
A header name type. Each has a corresponding value type.
var hashValue: Int
A header name type. Each has a corresponding value type.
protocol HTTPRequest: class
An HTTP based request object.
Contains all HTTP header and content data submitted by the client.
var method: HTTPMethod { get set }
The HTTP request method.
var queryParams: [(String, String)] { get }
The parsed and decoded query/search arguments.
var protocolVersion: (Int, Int) { get }
The HTTP protocol version. For example (1, 0), (1, 1), (2, 0)
var remoteAddress: (host: String, port: UInt16) { get }
The IP address and connecting port of the client.
var serverAddress: (host: String, port: UInt16) { get }
The IP address and listening port for the server.
var serverName: String { get }
The canonical name for the server.
var documentRoot: String { get }
The server's document root from which static file content will generally be served.
var connection: NetTCP { get }
The TCP connection for this request.
var urlVariables: [String:String] { get set }
Any URL variables acquired during routing the path to the request handler.
var scratchPad: [String:Any] { get set }
This dictionary is available for general use.
It permits components which might be loosely coupled and called at differing times
in the request execution process (eg. request/response filters) to pass messages or store
data for later use.
func header(_ named: HTTPRequestHeader.Name) -> String?
Returns the requested incoming header value.
func addHeader(_ named: HTTPRequestHeader.Name, value: String)
Add a header to the response.
No check for duplicate or repeated headers will be made.
func setHeader(_ named: HTTPRequestHeader.Name, value: String)
Set the indicated header value.
If the header already exists then the existing value will be replaced.
var postParams: [(String, String)] { get }
Any parsed and decoded POST body parameters.
If the POST content type is multipart/form-data then these will contain only the
non-file upload parameters.
var postBodyBytes: [UInt8]? { get set }
POST body data as raw bytes.
If the POST content type is multipart/form-data then this will be nil.
var postBodyString: String? { get }
POST body data treated as UTF-8 bytes and decoded into a String, if possible.
If the POST content type is multipart/form-data then this will be nil.
var postFileUploads: [MimeReader.BodySpec]? { get }
If the POST content type is multipart/form-data then this will contain the decoded form
parameters and file upload data.
This value will be nil if the request is not POST or did not have a multipart/form-data
content type.
extension HTTPRequest
func param(name: String, defaultValue: String? = nil) -> String?
Returns the first GET or POST parameter with the given name.
Returns the supplied default value if the parameter was not found.
func params(named: String) -> [String]
Returns all GET or POST parameters with the given name.
func params() -> [(String, String)]
Returns all GET or POST parameters.
extension HTTPRequest
var uri: String
Returns the full request URI.
var cookies: [(String, String)]
Returns all the cookie name/value pairs parsed from the request.
struct HTTPCookie
This bundles together the values which will be used to set a cookie in the outgoing response
enum Expiration
Cookie expiration type
case session
Session cookie with no explicit expiration
case relativeSeconds(Int)
Expiratiuon in a number of seconds from now
case absoluteSeconds(Int)
Expiration at an absolute time given in seconds from epoch
case absoluteDate(String)
Custom expiration date string
var name: String
Cookie name
var value: String
Cookie value
var domain: String?
Cookie domain
var expires: Expiration?
Cookie expiration
var secure: Bool?
Cookie secure flag
var httpOnly: Bool?
Cookie http only flag
var sameSite: SameSite?
Cookie samesite flag
protocol HTTPResponse: class
An HTTP based response object.
Contains all header and body data which will be delivered to the client.
var request: HTTPRequest { get }
The request object which instigated this response.
var isStreaming: Bool { get set }
Indicate that the response should attempt to stream all outgoing data.
This is primarily used when the resulting content length can not be known.
var bodyBytes: [UInt8] { get set }
Body data waiting to be sent to the client.
This will be emptied after each chunk is sent.
func header(_ named: HTTPResponseHeader.Name) -> String?
Returns the requested outgoing header value.
func addHeader(_ named: HTTPResponseHeader.Name, value: String)
Add a header to the outgoing response.
No check for duplicate or repeated headers will be made.
func setHeader(_ named: HTTPResponseHeader.Name, value: String)
Set the indicated header value.
If the header already exists then the existing value will be replaced.
func push(callback: @escaping (Bool) -> ())
Push all currently available headers and body data to the client.
May be called multiple times.
func completed()
Indicate that the request has completed.
Any currently available headers and body data will be pushed to the client.
No further request related activities should be performed after calling this.
extension HTTPResponse
func appendBody(bytes: [UInt8])
Append data to the bodyBytes member.
func appendBody(string: String)
Append String data to the outgoing response.
All such data will be converted to a UTF-8 encoded [UInt8]
func setBody(bytes: [UInt8])
Set the bodyBytes member, clearing out any existing data.
func setBody(string: String)
Set the String data of the outgoing response, clearing out any existing data.
All such data will be converted to a UTF-8 encoded [UInt8]
func setBody(json: [String:Any]) throws
Encodes the Dictionary as a JSON string and converts that to a UTF-8 encoded [UInt8]
func addCookie(_ cookie: HTTPCookie)
Add a cookie to the outgoing response.
class MimeReader
This class is responsible for reading multi-part POST form data, including handling file uploads.
Data can be given for parsing in little bits at a time by calling the `addTobuffer` function.
Any file uploads which are encountered will be written to the temporary directory indicated when the `MimeReader` is created.
Temporary files will be deleted when this object is deinitialized.
var bodySpecs = [BodySpec]()
Array of BodySpecs representing each part that was parsed.
var boundary = ""
The boundary identifier.
class BodySpec
This class represents a single part of a multi-part POST submission
var fieldName = ""
The name of the form field.
var fieldValue = ""
The value for the form field.
Having a fieldValue and a file are mutually exclusive.
var contentType = ""
The content-type for the form part.
var fileName = ""
The client-side file name as submitted by the form.
var fileSize = 0
The size of the file which was submitted.
var tmpFileName = ""
The name of the temporary file which stores the file upload on the server-side.
var file: File?
The File object for the local temporary file.
func cleanup()
Clean up the BodySpec, possibly closing and deleting any associated temporary file.
func init(_ contentType: String, tempDir: String = "/tmp/")
Initialize given a Content-type header line.
- parameter contentType: The Content-type header line.
- parameter tempDir: The path to the directory in which to store temporary files. Defaults to "/tmp/".
func addToBuffer(bytes byts: [UInt8])
Add data to be parsed.
- parameter bytes: The array of UInt8 to be parsed.
func addToBuffer(bytes byts: UnsafePointer<UInt8>, length: Int)
Add data to be parsed.
- parameter bytes: The array of UInt8 to be parsed.
var isMultiPart: Bool
Returns true of the content type indicated a multi-part form.
struct MimeType: ExpressibleByStringLiteral, CustomStringConvertible, Comparable
Represents a media type, consisting of a top-level type and a subtype.
May also possess parameters which adjust or qualify the media type.
MimeType parameters are not parsed or processed but are provided as-is as a String
typealias typealias UnicodeScalarLiteralType = String
Required for StringLiteralConvertible
typealias typealias StringLiteralType = String
Required for StringLiteralConvertible
var longType: String
top-level/sub-type; parameters
var shortType: String
top-level/sub-type
var type: TopType
Top-level type
var parameters: String?
Parameters, if any.
func init(type: TopType, subType: String, parameters: String?)
Initialize with top-level and sub-type.
Sub-type may contain parameters which will be separated.
func init(type: TopType, subType: String)
Initialize with top-level and sub-type.
Sub-type may contain parameters which will be separated.
func init(extension ext: String)
Initialize by looking up the media type for the given file extension.
If the extension is not a known file type, the MimeType will default to
application/octet-stream.
func init(_ value: String)
Initialize by parsing a String in the form "type/subtype; params".
func init(stringLiteral value: StringLiteralType)
Initialize by parsing a String in the form "type/subtype; params".
func init(unicodeScalarLiteral value: String)
Initialize by parsing a String in the form "type/subtype; params".
func init(extendedGraphemeClusterLiteral value: String)
Initialize by parsing a String in the form "type/subtype; params".
var description: String
Convert the MimeType into a String.
static func func forExtension(_ ext: String) -> String
Returns the mime type for the given extension. Defaults to application/octet-stream.
@deprecated
static func func ==(lhs: MimeType, rhs: MimeType) -> Bool
Returns the mime type for the given extension. Defaults to application/octet-stream.
@deprecated
static func func <(lhs: MimeType, rhs: MimeType) -> Bool
Returns the mime type for the given extension. Defaults to application/octet-stream.
@deprecated
protocol RouteNavigator: CustomStringConvertible
Object which maps uris to handler.
RouteNavigators are given to the HTTPServer to control its content generation.
typealias typealias RequestHandler = (HTTPRequest, HTTPResponse) -> ()
Function which receives request and response objects and generates content.
struct Routes
A group of routes. Add one or more routes to this object then call its navigator property to get the RouteNavigator.
Can be created with a baseUri. All routes which are added will have their URIs prefixed with this value.
func init()
Initialize with no baseUri.
func init(baseUri: String)
Initialize with a baseUri.
func init(_ routes: [Route])
Initialize with a array of Route.
func init(baseUri: String, routes: [Route])
Initialize with a baseUri and array of Route.
func mutating func add(_ routes: Routes)
Add all the routes in the Routes object to this one.
func mutating func add(_ routes: [Route])
Add all the routes in the Routes array to this one.
func mutating func add(uri: String, handler: @escaping RequestHandler)
Add the given uri and handler as a route.
This will add the route for all standard methods.
func mutating func add(uris: [String], handler: @escaping RequestHandler)
Add the given method, uris and handler as a route.
This will add the route for all standard methods.
var navigator: RouteNavigator
Return the RouteNavigator for this object.
struct StaticFileHandler
A web request handler which can be used to return static disk-based files to the client.
Supports byte ranges, ETags and streaming very large files.
func init(documentRoot: String, allowResponseFilters: Bool = false)
Public initializer given a document root.
If allowResponseFilters is false (which is the default) then the file will be sent in
the most effecient way possible and output filters will be bypassed.
func handleRequest(request: HTTPRequest, response: HTTPResponse)
Main entry point. A registered URL handler should call this and pass the request and response objects.
After calling this, the StaticFileHandler owns the request and will handle it until completion.