RouterResponse

public class RouterResponse

The RouterResponse class is used to define and work with the response that will be sent by the Router. It contains and allows access to the HTTP response code (e.g. 404 “Not Found”), the HTTP Headers and the body of the response. It can also render template files, using a template engine registered to the router.

Usage Example:

In this example “response” is an instance of the class RouterResponse. The content type and status code of the response are set. The String “Hello world” is added to the body and the response is transmitted.

router.get("/example") { _, response, next in
    response.headers["Content-Type"] = "text/html"
    response.status(.OK)
    try response.send("Hello world").end()
}

Properties

  • Set of cookies to return with the response.

    Declaration

    Swift

    public var cookies: [String : HTTPCookie]
  • Optional error value.

    Declaration

    Swift

    public var error: Swift.Error?
  • HTTP headers of the response.

    Declaration

    Swift

    public var headers: Headers
  • HTTP status code of the response.

    Declaration

    Swift

    public var statusCode: HTTPStatusCode { get set }
  • User info. Can be used by middlewares and handlers to store and pass information on to subsequent handlers.

    Declaration

    Swift

    public var userInfo: [String : Any]
  • Add a cookie to the response.

    This function creates an HTTPCookie from the provided attributes and adds it to the cookies dictionary.

    Declaration

    Swift

    public func addCookie(name: String, value: String, domain: String, path: String, otherAttributes: [AdditionalCookieAttribute]? = nil)

    Parameters

    name

    The cookie’s name.

    value

    The cookie‘s value.

    domain

    The domain of the cookie.

    path

    The cookie’s path.

    otherAttributes

    An array of any other optional cookie attributes

End

  • End the response.

    Throws

    Socket.Error if an error occurred while writing to a socket.

    Declaration

    Swift

    public func end() throws

Status Code

  • Set the status code.

    Declaration

    Swift

    @discardableResult
    public func status(_ status: HTTPStatusCode) -> RouterResponse

    Parameters

    status

    The HTTP status code object.

    Return Value

    This RouterResponse.

Redirect

  • Redirect to path with status code.

    Throws

    Socket.Error if an error occurred while writing to a socket.

    Declaration

    Swift

    @discardableResult
    public func redirect(_ path: String, status: HTTPStatusCode = .movedTemporarily) throws -> RouterResponse

    Return Value

    This RouterResponse.

Render

  • Render a resource using Router’s template engine.

    Throws

    TemplatingError if no file extension was specified or there is no template engine defined for the extension.

    Declaration

    Swift

    @discardableResult
    public func render(_ resource: String, context: [String: Any],
                       options: RenderingOptions = NullRenderingOptions()) throws -> RouterResponse

    Parameters

    resource

    The resource name without extension.

    context

    A dictionary of local variables of the resource.

    options

    Rendering options, specific per template engine

    Return Value

    This RouterResponse.

  • Render a resource using Router’s template engine.

    Throws

    TemplatingError if no file extension was specified or there is no template engine defined for the extension.

    Declaration

    Swift

    @discardableResult
    public func render<T: Encodable>(_ resource: String, with value: T, forKey key: String? = nil,
                       options: RenderingOptions = NullRenderingOptions()) throws -> RouterResponse

    Parameters

    resource

    The resource name without extension.

    with

    A value that conforms to Encodable that is used to generate the content.

    forKey

    A value used to match the Encodable value to the correct variable in a template file. The forKey value should match the desired variable in the template file.

    options

    Rendering options, specific per template engine

    Return Value

    This RouterResponse.

  • Render a resource using Router’s template engine.

    Throws

    TemplatingError if no file extension was specified or there is no template engine defined for the extension.

    Declaration

    Swift

    @discardableResult
    public func render<I: Identifier, T: Encodable>(_ resource: String, with values: [(I, T)], forKey key: String,
                                   options: RenderingOptions = NullRenderingOptions()) throws -> RouterResponse

    Parameters

    resource

    The resource name without extension.

    with

    An array of tuples of type (Identifier, Encodable). The Encodable values are used to generate the content.

    forKey

    A value used to match the Encodable values to the correct variable in a template file. The forKey value should match the desired variable in the template file.

    options

    Rendering options, specific per template engine

    Return Value

    This RouterResponse.

Set Properties

  • Set the pre-flush lifecycle handler and return the previous one.

    Declaration

    Swift

    public func setOnEndInvoked(_ newOnEndInvoked: @escaping LifecycleHandler) -> LifecycleHandler

    Parameters

    newOnEndInvoked

    The new pre-flush lifecycle handler.

    Return Value

    The old pre-flush lifecycle handler.

  • Set the written data filter and return the previous one.

    Declaration

    Swift

    public func setWrittenDataFilter(_ newWrittenDataFilter: @escaping WrittenDataFilter) -> WrittenDataFilter

    Parameters

    newWrittenDataFilter

    The new written data filter.

    Return Value

    The old written data filter.

Content Negotiation

  • Perform content-negotiation on the Accept HTTP header on the request, when present.

    Uses request.accepts() to select a handler for the request, based on the acceptable types ordered by their quality values. If the header is not specified, the default callback is invoked. When no match is found, the server invokes the default callback if exists, or responds with 406 “Not Acceptable”. The Content-Type response header is set when a callback is selected.

    Throws

    Socket.Error if an error occurred while writing to a socket.

    Declaration

    Swift

    public func format(callbacks: [String : ((RouterRequest, RouterResponse) -> Void)]) throws

    Parameters

    callbacks

    A dictionary that maps content types to handlers.

Send String

  • Send a UTF-8 encoded string.

    Declaration

    Swift

    @discardableResult
    public func send(_ str: String) -> RouterResponse

    Parameters

    str

    The string to send.

    Return Value

    This RouterResponse.

  • Send an optional string. If the String? can be unwrapped it is sent as a String, otherwise the empty string (“”) is sent.

    Declaration

    Swift

    @discardableResult
    public func send(_ str: String?) -> RouterResponse

    Parameters

    str

    The string to send.

    Return Value

    This RouterResponse.

  • Set the HTTP status code of the RouterResponse and send the String description of the HTTP status code.

    Declaration

    Swift

    public func send(status: HTTPStatusCode) -> RouterResponse

    Parameters

    status

    The HTTP status code.

    Return Value

    This RouterResponse.

Send Data

  • Send data.

    Declaration

    Swift

    @discardableResult
    public func send(data: Data) -> RouterResponse

    Parameters

    data

    The data to send.

    Return Value

    This RouterResponse.

  • Send a file.

    Throws

    An error in the Cocoa domain, if the file cannot be read.

    Note

    Sets the Content-Type header based on the “extension” of the file. If the fileName is relative, it is relative to the current directory.

    Declaration

    Swift

    @discardableResult
    public func send(fileName: String) throws -> RouterResponse

    Parameters

    fileName

    The name of the file to send.

    Return Value

    This RouterResponse.

  • Set headers and attach file for downloading.

    Throws

    An error in the Cocoa domain, if the file cannot be read.

    Declaration

    Swift

    public func send(download: String) throws

    Parameters

    download

    The file to download.

  • Sets the Content-Type header as application/json, Serializes an array into JSON data and sends the data. If the data is not a valid JSON structure, it will not be sent and a warning will be logged.

    Declaration

    Swift

    @discardableResult
    public func send(json: [Any]) -> RouterResponse

    Parameters

    json

    The array to send in JSON format.

    Return Value

    This RouterResponse.

  • Sets the Content-Type header as “application/json”, Serializes a dictionary into JSON data and sends the data. If the data is not a valid JSON structure, it will not be sent and a warning will be logged.

    Declaration

    Swift

    @discardableResult
    public func send(json: [String : Any]) -> RouterResponse

    Parameters

    json

    The Dictionary to send in JSON format as a hash.

    Return Value

    This RouterResponse.

Send Encodable

  • Sends an Encodable type, encoded using the preferred BodyEncoder based on the “Accept” header sent in the request, and sets the Content-Type header appropriately. If no Accept header was provided, or if no suitable encoder is registered with the router, the encoder corresponding to the defaultResponseMediaType will be used.

    Declaration

    Swift

    @discardableResult
    public func send<T>(_ obj: T) -> RouterResponse where T : Encodable

    Parameters

    obj

    The Codable object to send.

    Return Value

    This RouterResponse.

  • Sets the Content-Type header as “application/json”, Encodes an Encodable object into data using a JSONEncoder() and sends the data.

    Declaration

    Swift

    @discardableResult
    public func send<T>(json: T) -> RouterResponse where T : Encodable

    Parameters

    json

    The JSON Encodable object to send.

    Return Value

    This RouterResponse.

  • Encodes an Encodable object into data using a JSONEncoder() and sends the data with JSONP callback.

    Throws

    JSONPError.invalidCallbackName if the the callback query parameter of the request URL is missing or its value is empty or contains invalid characters (the set of valid characters is the alphanumeric characters and []$._).

    Declaration

    Swift

    public func send<T>(jsonp: T, callbackParameter: String = "callback") throws -> RouterResponse where T : Encodable

    Parameters

    json

    The JSON object to send.

    callbackParameter

    The name of the URL query parameter whose value contains the JSONP callback function.

    Return Value

    This RouterResponse.