Swiftra 0.4.0

Swiftra 0.4.0

mtgto 维护。



Swiftra 0.4.0

  • 作者:
  • mtgto

Swiftra

Cocoapods Platforms build status

一个小巧的类似 Sinatra 的 Swift 网络框架。

Swiftra 是在 SwiftNIO 之上的一个小包装。

示例

import Swiftra

struct ExampleError: Error {}

let app = App {
    get("/") { req in
        .text("Hello, world!")
    }

    get("/html") { req in
        .text("<html><body>Hello from Swiftra</body></html>", contentType: ContentType.textHtml.withCharset())
    }

    // path parameters
    get("/hello/:name") { req in
        .text("Hello \(req.params("name", default: "guest"))")
    }

    // convert Encodable value into JSON
    get("/json") { req in
        Response(json: ["Hello": "World!"])!
    }

    // asynchronous
    futureGet("/future") { req in
        let promise = req.makePromise(of: String.self)
        _ = req.eventLoop.scheduleTask(in: .seconds(1)) {
            promise.succeed("Hello from future")
        }
        return promise.futureResult.map { .text($0) }
    }

    // No route matches
    notFound { req in
        .text("Not Found", status: .notFound)
    }

    // Example of error handling. See also below `error`
    get("/error") { req in
        throw ExampleError()
    }

    // unhandled error handler
    error { req, error in
        .text("Error", status: .internalServerError)
    }
}

// You can add routes
app.addRoutes {
    get("/addRoute") { req in
        .text("New route is added")
    }
}

// Set default response headers
app.defaultHeaders = [("Server", "SwiftraExample/1.0.0")]

try! app.start(1337)
// You can customize bind address
// try! app.start(1337, host: "localhost")

安装

Swift 包管理器 (SPM)

https://github.com/mtgto/Swiftra 添加到 Swift 包的依赖关系中。

Cocoapods

pod 'Swiftra', '~> 0.3' 添加到您的 Podfile 中。

功能

  • 路由
  • 访问路径参数
  • 访问查询参数

至v1.0.0路线图

  • 请求头组件访问辅助器
    • 查询字符串
    • 片段
    • Cookie
  • 请求数据访问辅助器
    • x-www-form-urlencoded 数据
    • JSON 请求
  • GET 以外的 HTTP 方法
  • 错误处理
  • 文件上传
    • 大文件上传
  • 更多性能

贡献

在提交贡献之前,请使用swift-format格式化Swift代码。

$ swift-format --configuration .swift-format --in-place YourAwesomeCode.swift

推荐使用pre-commit

$ brew install pre-commit
$ pre-commit install

致谢

非常感谢 A µTutorial on SwiftNIO 2

许可

Apache License 2.0。

参见 LICENSE.txt

作者

@mtgto