HTTPServerResponse

public class HTTPServerResponse : ServerResponse

This class implements the ServerResponse protocol for outgoing server responses via the HTTP protocol. Data and Strings can be written.

The example below uses this in its response parameter, with the example requesting a connection be upgraded and catch any errors that occur.

Usage Example:

 func upgradeConnection(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) {
     guard let protocols = request.headers["Upgrade"] else {
         do {
             response.statusCode = HTTPStatusCode.badRequest
             try response.write(from: "No protocol specified in the Upgrade header")
             try response.end()
         }
         catch {
             Log.error("Failed to send error response to Upgrade request")
         }
         return
     }
 }
  • The HTTP headers to be sent to the client as part of the response.

    Usage Example:

    ServerResponse.headers["Content-Type"] = ["text/plain"]
    

    Declaration

    Swift

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

    Usage Example:

    ServerResponse.statusCode = HTTPStatusCode.badRequest
    

    Declaration

    Swift

    public var statusCode: HTTPStatusCode? { get set }
  • Write a string as a response.

    Throws

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

    Usage Example:

     try ServerResponse.write(from: "Some string")
    

    Declaration

    Swift

    public func write(from string: String) throws

    Parameters

    from

    String data to be written.

  • Write data as a response.

    Throws

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

    Usage Example:

    try ServerResponse.write(from: someData)
    

    Declaration

    Swift

    public func write(from data: Data) throws

    Parameters

    from

    Data object that contains the data to be written.

  • Write a String to the body of a HTTP response and complete sending the HTTP response.

    Throws

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

    Usage Example:

    try ServerResponse.end("Some string")
    

    Declaration

    Swift

    public func end(text: String) throws

    Parameters

    text

    String to write to a socket.

  • Complete sending the HTTP response.

    Throws

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

    Usage Example:

    try ServerResponse.end()
    

    Declaration

    Swift

    public func end() throws
  • Reset this response object back to its initial state.

    Usage Example:

    try ServerResponse.reset()
    

    Declaration

    Swift

    public func reset()