Skip to content

Instantly share code, notes, and snippets.

@adam-fowler
Last active December 3, 2021 15:12
Show Gist options
  • Save adam-fowler/a098370f5988341ead266a28e6741dc2 to your computer and use it in GitHub Desktop.
Save adam-fowler/a098370f5988341ead266a28e6741dc2 to your computer and use it in GitHub Desktop.
Local web server written in swift

For this to work you need swift-sh installed.

#!/usr/bin/env swift-sh

import ArgumentParser   // apple/swift-argument-parser
import HummingbirdFoundation  // hummingbird-project/hummingbird

struct WebServer: ParsableCommand {
    @Option(name: .shortAndLong)
    var port: Int = 8001

    @Argument
    var folder: String = "."

    func run() throws {
        let app = HBApplication(
            configuration: .init(
                address: .hostname("127.0.0.1", port: self.port),
                serverName: "WebServer"
            )
        )
        app.middleware.add(HBFileMiddleware(self.folder, application: app))
        app.middleware.add(HBLogRequestsMiddleware(.info))
        try app.start()
        app.wait()
    }
}

WebServer.main()

This was so useful I turned it into a package https://github.com/adam-fowler/swift-web

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment