Classes
The following classes are available globally.
-
Routerprovides 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
RouterMiddlewareprotocol. - Routing requests to a
TemplateEngineto generate the appropriate output. - Serving the landing page when someone makes an HTTP request with a path of slash (/).
Declaration
- Routing requests to closures of type
-
Facilities for creating, starting and stopping Kitura-based servers.
Usage Example:
In this example, a
Routeris 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 theKitura.run()function (note that this function does not return). The route can then be accessed by visitinghttp://localhost:8080.
See morelet router = Router() router.get("/") { request, response, next in response.send("Hello world") next() } Kitura.addHTTPServer(onPort: 8080, onAddress: "localhost", with: router) Kitura.run()Declaration
Swift
public class Kitura
-
Create an on the fly
See moreRouterMiddlewarefrom aRouterHandlerclosure.Declaration
Swift
public class RouterMiddlewareGenerator : RouterMiddleware
-
The
RouterRequestclass is used to interact with incoming HTTP requests to the Router. It contains and allows access to the request’sHeadersandBodyas 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.
See morelet router = Router() router.post("/") { request, response, next in let body = request.readString() response.send(body) next() }Declaration
Swift
public class RouterRequest
-
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 HTTPHeadersand 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.
See morerouter.get("/example") { _, response, next in response.headers["Content-Type"] = "text/html" response.status(.OK) try response.send("Hello world").end() }Declaration
Swift
public class RouterResponse
-
The
BodyParserparses the body of the request prior to sending it to the handler. It reads the Content-Type of the message header and populates theRouterRequestbody field with a correspondingParsedBodyenumeration.In order for the BodyParser to be used it must first be registered with any routes that are interested in the
ParsedBodypayload.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-TypeEach 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,
ParsedBodywill benil.Usage Example:
In this example, all routes to the BodyParser middleware are registered to the
BodyParsermiddleware. 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 moreDeclaration
Swift
public class BodyParser : RouterMiddleware -
The
BodyParserMultiValueis a subclass ofBodyParser, which differs in behaviour when decoding urlencoded parameters with multiple values (such as&a=1&a=2).Whereas
BodyParserwill produce a comma-separated list of values:["a": "1,2"]which may be accessed byParsedBody.urlEncoded,BodyParserMultiValuewill produce an array of values:["a": ["1", "2"]], accessed byParsedBody.urlEncodedMultiValue.This enables you to accept multiple values which may themselves contain commas.
See moreDeclaration
Swift
public class BodyParserMultiValue : BodyParser
-
The
ContentTypeclass 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
ContentTypeinstance 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”.
See morelet contentType = ContentType.sharedInstance let result = contentType.getContentType(forFileName: "foo.png") print(String(describing: result)) // Prints Optional("image/png")Declaration
Swift
public class ContentType
-
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
StaticFileServeron 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.
See morelet router = Router() router.all("/example", middleware: StaticFileServer(path: "./files"))Declaration
Swift
open class StaticFileServer : RouterMiddleware
View on GitHub
Classes Reference