Classes

The following classes are available globally.

BufferList

  • This class provides an implementation of a buffer that can be added to and taken from in chunks. Data is always added to the end of the buffer (using BufferList.append(...) and taken out of the buffer (using BufferList.fill(...)) from the beginning towards the end. The location indicating where the next chunk of data will be taken from is maintained, this location can then be reset to enable data to be taken out of the buffer from the beginning again.

    In the below example, we create an empty BufferList instance. You can then append data to your BufferList instance, in our case writeBuffer. We then make two seperate appends. When writeBuffer contains the data which you wish to write out you can use BufferList.fill(...) to write out the data from the buffer to your chosen location, which in this case is finalArrayOfNumbers.

    Usage Example:

    var writeBuffer = BufferList()
    
    let firstArrayOfNumbers: [UInt8] = [1,2,3,4]
    
    // Append a set of data to the 'writeBuffer' object
    writeBuffer.append(bytes: UnsafePointer<UInt8>(firstArrayOfNumbers),
                       length: MemoryLayout<UInt8>.size * firstArrayOfNumbers.count)
    
    // Number of bytes stored in the 'writeBuffer' object
    print(writeBuffer.count)
    // Prints "4"
    
    let secondArrayOfNumbers: [UInt8] = [5,6,7,8]
    
    // Append a second set of data to the 'writeBuffer' object
    writeBuffer.append(bytes: UnsafePointer<UInt8>(secondArrayOfNumbers),
                       length: MemoryLayout<UInt8>.size * secondArrayOfNumbers.count)
    
    print(writeBuffer.count)
    // Prints "8"
    
    let finalArrayOfNumbers: [UInt8] = [0,0,0,0,0,0,0,0,9,10]
    
    // Fill the destination buffer 'finalArrayOfNumbers' with the data from 'writeBuffer'
    let count = writeBuffer.fill(buffer: UnsafeMutableRawPointer(mutating: finalArrayOfNumbers)
                           .assumingMemoryBound(to: UInt8.self), length: ((MemoryLayout<UInt8>.size)
                           * finalArrayOfNumbers.count))
    
    print("count = \(count), buffer is = \(finalArrayOfNumbers)" )
    // Prints "count = 8, buffer is = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]"
    
    See more

    Declaration

    Swift

    public class BufferList

ClientRequest

  • This class provides a set of low level APIs for issuing HTTP requests to another server. A new instance of the request can be created, along with options if the user would like to specify certain parameters such as HTTP headers, HTTP methods, host names, and SSL credentials. Data and String objects can be added to a ClientRequest too, and URLs can be parsed.

    Usage Example:

    //Function to create a new `ClientRequest` using a URL.
     public static func request(_ url: String, callback: @escaping ClientRequest.Callback) -> ClientRequest {
         return ClientRequest(url: url, callback: callback)
     }
    
     //Create a new `ClientRequest` using a URL.
     let request = HTTP.request("http://localhost/8080") {response in
         ...
     }
    
    See more

    Declaration

    Swift

    public class ClientRequest

ClientResponse

  • This class describes the response sent by the remote server to an HTTP request sent using the ClientRequest class. Data or Strings can be read in, and URLs can be parsed.

    Usage Example:

    //The `ClientResponse` object that describes the response that was received from the remote server is used in a callback.
    public typealias Callback = (ClientResponse?) -> Void
    
    See more

    Declaration

    Swift

    public class ClientResponse
  • The “root” class for the FastCGI server implementation. A FastCGIServer instance can be created.

    Usage Example:

    //Implement a `FastCGI` server.
    let server = FastCGI.createServer()
    
    See more

    Declaration

    Swift

    public class FastCGI
  • A server that listens for incoming HTTP requests that are sent using the FastCGI protocol. This can be used to create a new FastCGIServer and have it listen for conenctions and handle a new client FastCGI request.

    Usage Example:

    //Create a `FastCGI` server on a specified port.
    let server = try FastCGIServer.listen(on: port, delegate: delegate)
    
    See more

    Declaration

    Swift

    public class FastCGIServer : Server
  • The FastCGIServerRequest class implements the ServerRequest protocol for incoming HTTP requests that come in over a FastCGI connection. This can be used to read data from the body of the request and process the original request URI.

    Usage Example:

     //Create a `FastCGIServerRequest` to handle a new client FastCGI request.
     let request = FastCGIServerRequest(socket: clientSocket)
    
     //Handle a new client FastCGI request.
     request.parse() { status in
         switch status {
         case .success:
             ...
         break
         case .unsupportedRole:
             ...
         break
         default:
             ...
         break
         }
     }
    
    See more

    Declaration

    Swift

    public class FastCGIServerRequest : ServerRequest
  • The FastCGIServerRequest class implements the ServerResponse protocol for incoming HTTP requests that come in over a FastCGI connection.

    Usage Example:

     //Create a `FastCGIServerResponse` object with socket and request parameters.
     let response = FastCGIServerResponse(socket: clientSocket, request: request)
     ...
     //Set the status code.
     response.statusCode = HTTPStatusCode.badRequest
     ...
     //Write a String to the `FastCGIServerResponse` object.
     try response.write(from: "Some String")
     ...
     //Stop the `FastCGIServerResponse` object.
     try response.end()
    
    See more

    Declaration

    Swift

    public class FastCGIServerResponse : ServerResponse

HTTP

  • A set of helpers for HTTP: status codes mapping, server and client request creation.

    Usage Example:

     //Create a HTTP server.
     let server = HTTP.createServer()
    
     //Create a new a `ClientRequest` instance using a URL.
     let request = HTTP.request("http://localhost/8080") {response in
     ...
     }
    
     //Get a `ClientRequest` instance from a URL.
     let getHTTP = HTTP.get("http://localhost/8080") { response in
     ...
     }
    
     HTTP.escape(url: testString)
    
    See more

    Declaration

    Swift

    public class HTTP

HTTPServer

  • An HTTP server that listens for connections on a socket.

    Usage Example:

     //Create a server that listens for connections on a specified socket.
     let server = try HTTPServer.listen(on: 0, delegate: delegate)
     ...
     //Stop the server.
     server.stop()
    
    See more

    Declaration

    Swift

    public class HTTPServer : Server

HTTPServerRequest

  • This class implements the ServerRequest protocol for incoming sockets that are communicating via the HTTP protocol. Data and Strings can be read in.

    Usage Example:

     func handlePost(request: ServerRequest, response: ServerResponse) {
         var body = Data()
         do {
             let length = try request.readAllData(into: &body)
             let result = "Read \(length) bytes"
             response.headers["Content-Type"] = ["text/plain"]
             response.headers["Content-Length"] = ["\(result.count)"]
    
             try response.end(text: result)
         }
         catch {
             print("Error reading body or writing response")
         }
     }
    
    See more

    Declaration

    Swift

    public class HTTPServerRequest : ServerRequest

HTTPServerResponse

  • 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
         }
     }
    
    See more

    Declaration

    Swift

    public class HTTPServerResponse : ServerResponse
  • This class processes the data sent by the client after the data was read. The data is parsed, filling in a HTTPServerRequest object. When the parsing is complete, the ServerDelegate is invoked.

    Usage Example:

     //Create an `IncomingHTTPSocketProcessor` object.
     var processor : IncomingHTTPSocketProcessor?
    
     //Write from an NSMutableData buffer.
     processor.write(from: NSMutableData)
    
     //Write from a data object.
     processor.write(from: utf8, length: utf8Length)
    
    See more

    Declaration

    Swift

    public class IncomingHTTPSocketProcessor : IncomingSocketProcessor

URLParser

  • Splits and parses URLs into components - scheme, host, port, path, query string etc. according to the following format:

    scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]

    Usage Example:

     // Initialize a new URLParser instance, and check whether or not a connection has been established.
     let url = "http://user:password@sample.host.com:8080/a/b/c?query=somestring#hash".data(using: .utf8)!
     let urlParser = URLParser(url: url, isConnect: false)
    
    See more

    Declaration

    Swift

    public class URLParser : CustomStringConvertible
  • A class that abstracts out the HTTP header APIs of the ServerRequest and ServerResponse protocols.

    Usage Example:

     public var headers: HeadersContainer { return httpParser?.headers ?? HeadersContainer() }
    
    See more

    Declaration

    Swift

    public class HeadersContainer
    extension HeadersContainer: Collection
  • This class handles incoming sockets to the HTTPServer. The data sent by the client is read and passed to the current IncomingDataProcessor.

    Note

    The IncomingDataProcessor can change due to an Upgrade request.

    Note

    This class uses different underlying technologies depending on:

    1. On Linux, if no special compile time options are specified, epoll is used
    2. On OSX, DispatchSource is used
    3. On Linux, if the compile time option -Xswiftc -DGCD_ASYNCH is specified,
       DispatchSource is used, as it is used on OSX.
    

    Usage Example:

     func upgrade(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) -> (IncomingSocketProcessor?, Data?, String?) {
         let (processor, responseText) = upgrade(handler: handler, request: request, response: response)
    
         if let responseText = responseText {
             return (processor, responseText.data(using: .utf8), "text/plain")
         }
         return (processor, nil, nil)
     }
    
    See more

    Declaration

    Swift

    public class IncomingSocketHandler
  • The IncomingSocketManager class is in charge of managing all of the incoming sockets. In particular, it is in charge of:

    1. On Linux when no special compile options are specified: a. Creating the epoll handle b. Adding new incoming sockets to the epoll descriptor for read events c. Running the “thread” that does the epoll_wait
    2. Creating and managing the IncomingSocketHandlers and IncomingHTTPDataProcessors (one pair per incomng socket)
    3. Cleaning up idle sockets, when new incoming sockets arrive.

    Usage Example:

     //Create a manager to manage all of the incoming sockets.
     var manager: IncomingSocketManager?
    
     override func setUp() {
         manager = IncomingSocketManager()
     }
    
    See more

    Declaration

    Swift

    public class IncomingSocketManager
  • A class that provides a set of helper functions that enables a caller to wait for a group of listener blocks to finish executing.

    Usage Example:

     //Wait for all of the listeners to stop.
     ListenerGroup.waitForListeners()
    
     //Enqueue a block of code on a given queue, assigning it to the listener group in the process (so we can wait on it later).
     ListenerGroup.enqueueAsynchronously(on: DispatchQueue.global(), block: queuedBlock)
    
    See more

    Declaration

    Swift

    public class ListenerGroup

SPIUtils

  • A set of utility functions. Includes formatting the given time and date for use in HTTP, where the default value is the current time.

    Usage Example:

    //Format the given date for use in HTTP
    SPIUtils.httpDate()
    
    See more

    Declaration

    Swift

    public class SPIUtils