Classes

The following classes are available globally.

  • Router provides the external interface for routing requests to the appropriate code to handle them. This includes:

    • Routing requests to closures of type RouterHandler
    • Routing requests to the handle function of classes that implement the RouterMiddleware protocol.
    • Routing requests to a TemplateEngine to generate the appropriate output.
    • Serving the landing page when someone makes an HTTP request with a path of slash (/).
    See more

    Declaration

    Swift

    public class Router
    extension Router : RouterMiddleware
    extension Router : ServerDelegate
  • Facilities for creating, starting and stopping Kitura-based servers.

    Usage Example:

    In this example, a Router is created, and a single route registered that responds to an HTTP GET request on “/” with a plain text response. An HTTP server is created on port 8080, and is started with the Kitura.run() function (note that this function does not return). The route can then be accessed by visiting http://localhost:8080.

    let router = Router()
    router.get("/") { request, response, next in
        response.send("Hello world")
        next()
    }
    Kitura.addHTTPServer(onPort: 8080, onAddress: "localhost", with: router)
    Kitura.run()
    
    See more

    Declaration

    Swift

    public class Kitura

RouterMiddlewareGenerator

RouterRequest

  • The RouterRequest class is used to interact with incoming HTTP requests to the Router. It contains and allows access to the request’s Headers and Body as well as other properties of the request. It can also perform content negotiation based on the request’s “Accept” header.

    Usage Example:

    In this example “request” is an instance of the class RouterRequest. It is used by the server to read the body of the request as a String and send it back to the user.

    let router = Router()
    router.post("/") { request, response, next in
        let body = request.readString()
        response.send(body)
        next()
    }
    
    See more

    Declaration

    Swift

    public class RouterRequest

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()
    }
    
    See more

    Declaration

    Swift

    public class RouterResponse

BodyParser

  • The BodyParser parses the body of the request prior to sending it to the handler. It reads the Content-Type of the message header and populates the RouterRequest body field with a corresponding ParsedBody enumeration.

    In order for the BodyParser to be used it must first be registered with any routes that are interested in the ParsedBody payload.

    ParsedBody enumeration:

    The mappings from the incoming Content-Type to an internal representation of the body are as follows:

       .json([String: Any])          // "application/json"
       .text(String)                 // "text/*"
       .urlEncoded([String:String])  // "application/x-www-form-urlencoded"
       .multipart([Part])            // "multipart/form-data"
       .raw(Data)                    // Any other Content-Type
    

    Each case has a corresponding convenience property, e.g. asURLEncoded: [String:String], for accessing the associated data.

    Note: If you have not declared a Content-Type header, ParsedBody will be nil.

    Usage Example:

    In this example, all routes to the BodyParser middleware are registered to the BodyParser middleware. A request with “application/json”, ContentType header is received. It is then parsed as JSON and the value for “name” is returned in the response.

    router.all("/name", middleware: BodyParser())
    router.post("/name") { request, response, next in
        guard let jsonBody = request.parsedBody?.asJSON else {
            next()
            return
        }
        let name = jsonBody["name"] as? String ?? ""
        try response.send("Hello \(name)").end()
    }
    

    Note: When using Codable Routing in Kitura 2.x the BodyParser should not be registered to any codable routes (doing so will log the following error “No data in request. Codable routes do not allow the use of a BodyParser.” and the route handler will not be executed).

    See more

    Declaration

    Swift

    public class BodyParser : RouterMiddleware
  • The BodyParserMultiValue is a subclass of BodyParser, which differs in behaviour when decoding urlencoded parameters with multiple values (such as &a=1&a=2).

    Whereas BodyParser will produce a comma-separated list of values: ["a": "1,2"] which may be accessed by ParsedBody.urlEncoded, BodyParserMultiValue will produce an array of values: ["a": ["1", "2"]], accessed by ParsedBody.urlEncodedMultiValue.

    This enables you to accept multiple values which may themselves contain commas.

    See more

    Declaration

    Swift

    public class BodyParserMultiValue : BodyParser

ContentType

  • The ContentType class provides functions to determine the MIME content type for a given file extension. The user can pass in a complete file name e.g. “foo.png” or just the file extension e.g. “png”, or they can pass in both a MIME content type and a file extension and query whether they match.

    Usage Example:

    In this example, a ContentType instance is initialised called contentType. This instance is then used to obtain the MIME content type of the file “foo.png”, which is identified as “image/png”.

    let contentType = ContentType.sharedInstance
    let result = contentType.getContentType(forFileName: "foo.png")
    print(String(describing: result))
    // Prints Optional("image/png")
    
    See more

    Declaration

    Swift

    public class ContentType

StaticFileServer

  • A router middleware that serves static files from a given path. By default, it will serve files from the “/public” directory.

    Usage Example:

    The example below creates and registers a StaticFileServer on the “/example” route. When the router is running, A user can make a request that matches the “/example” path (e.g. localhost:8080/example/hello.html). The static file server would look inside its “/files” folder for a file with the same name as the path following “/example” (e.g. “hello.html”). If a file is found it is sent as a response to that request, otherwise the next handler is called.

    let router = Router()
    router.all("/example", middleware: StaticFileServer(path: "./files"))
    
    See more

    Declaration

    Swift

    open class StaticFileServer : RouterMiddleware