基于 async / await 的极简 HTTP 请求库
在 Swift 中使用 Foundation
发送 HTTP API 请求可能非常繁琐,需要使用 URL
、URLComponents
和 URLRequest
等多种类型来构建请求,然后在后续步骤中处理所有的编码和解码。虽然这段代码本身并不复杂,但当手动编写请求时,它会变得非常重复。
这个 Swift Package 的目标是提供一个极其精简、轻量级的抽象层,介于用户和 Foundation 中重复且繁琐的 HTTP 请求编写之间。
Mu 允许用户预先声明请求及其 body 和 header,以及端点等其他详细信息,以提高代码可读性,并消除使用 URLSession
发送 HTTP 请求时的样板代码。
未来 Swift Package Manager 似乎将取代 Carthage 和 CocoaPods,而且由于 SPM 已经内置在 Xcode 中,为什么不使用它呢?
要在 Xcode 中通过 SPM 安装 Mu,请转到 File
-> Add Packages...
并输入 https://github.com/nirma/mu
Mu 非常简单,它只有两个部分:一个是符合 HTTPRequest
协议的请求,另一个是用于发送请求的 Requester
。
let request = Request(
scheme: .https,
host: "api.github.com",
path: "/users/nirma",
method: .get,
headers: ["Accept": "application/vnd.github.v3+json"]
)
let requester = Requester(decoder: JSONDecoder())
Task {
do {
let (user, response) = try await requester.send(
request: request,
expect: ExpectedResponse.self // A `Decodable` type that is the expected response
)
...
} catch { ... }
}
POST
请求使用 HTTPBody
指定 body。HTTPBody
可以是原始 Data
,也可以是符合 Swifts
Encodable` 的类型。
let body = [
"username": "foobar42",
"email": "foobar42@github.com",
"password_hash": "34973274ccef6ab4dfaaf86599792fa9c3fe4689"
]
let request = Request(
scheme: .https,
host: "example.com",
path: "/user/create",
method: .post,
headers: ["Content-Type": "application/json"],
body: HTTPBody(body)
)
let requester = Requester(decoder: JSONDecoder())
Task {
do {
let (user, response) = try await requester.send(
request: request,
expect: ExpectedResponse.self // A `Decodable` type that is the expected response
)
...
} catch { ... }
}
HTTPRequest
是此库中所有请求都必须符合的协议。此库包含一个简单的类 Request
,它实现了此协议,并且纯粹为了方便而包含,请随意实现您自己的符合 HTTPRequest
的类型,或者使用或继承 Request
(如果适合您的需求)。
只需构造一个符合 HTTPRequester
的类型,并使用 send(request:expect)
方法发送您的请求。响应将被转换为由 expect
参数指定的类型,如果转换失败,将抛出异常。
Requester
开箱即用,并接受任何符合 AbstractDecoder
的解码类型。默认一致性已应用于 JSONDecoder
,因此对于期望 JSON 响应的请求,只需传入 JSONDecoder
即可
let requester = Requester(decoder: JSONDecoder())
如果 JSONDecoder
不是完成这项工作的正确工具,只需使您希望使用的类型符合 AbstractDecoder
并传入即可!
本库采用 MIT 许可证发布。有关详细信息,请参阅 LICENSE。