All pages
Powered by GitBook
1 of 3

Loading...

Loading...

Loading...

Listen for Requests

All Swift Cloud applications start with listening for an incoming HTTP request. This is accomplished by calling onIncomingRequest in your main handler function:

import Compute

@main
struct App {
    static func main() async throws {
        try await onIncomingRequest(handleIncomingRequest)
    }

    static func handleIncomingRequest(req: IncomingRequest, res: OutgoingResponse) async throws {
        print("Handling request:", req.url.pathname)
    }
}

Respond to Requests

Responding to HTTP requests is just as simple as listening for them, simply call the various send() methods on the OutgoingResponse object:

import Compute

@main
struct HelloCompute {
    static func main() async throws {
        try await onIncomingRequest(handleIncomingRequest)
    }

    static func handleIncomingRequest(req: IncomingRequest, res: OutgoingResponse) async throws {
        let text = "Hello, World."
        try await res.status(200).send(text)
    }
}

The Compute library provides various versions of send that allow you to pass JSON data, Encodable's, HTML, XML and raw bytes / streams of data.

Compute Runtime

The core library for building apps on Swift Cloud

.package(url: "https://github.com/AndrewBarba/swift-compute-runtime", from: "1.0.0")

The compute runtime provides bindings to the underlying WASM runtime giving you the ability to listen for HTTP requests, make outgoing HTTP requests, read dictionary and environment variables, and a whole lot more.

The library was designed with modern Swift features like async/await to make concurrent programing as easy and safe to use as possible. It also provides lower level abstractions for working directly with streaming data, giving developers the highest level of flexibility when working building their API's. One main advantage of building on the Fastly platform is the superior HTTP stack compared to other serverless platforms like AWS Lambda. Lambda does not have any ability to stream responses to clients and thus limits what you can do with binary data like images and MP3's. On Swift Cloud you have full control over streaming requests and responses.

To get started building apps on Swift Cloud, you must install the [Swift Compute Runtime]() using Swift Package Manager:

https://github.com/AndrewBarba/swift-compute-runtime