一个 Server Side Swift 库,用于执行 HTTP 请求,并返回格式化为提供的 Codable 对象类型的数据。
该库利用了 Perfect HTTP 和 CURL 库。
将以下内容添加到您的 Package.swift 文件的 dependencies 数组中
.package(url: "https://github.com/iamjono/codableRequest.git", "1.0.0"..<"2.0.0")
然后确保您已经执行了 swift package update
并重新生成您的 Xcode 项目文件。
您必须有一个符合 Codable
协议的结构体,以匹配您期望的响应。 在测试中使用的示例中,结果被转换为 HTTPbin
结构体类型,如下所示。 可以指定一个可选的错误类型,以包含自定义的错误格式。
此请求的完整形式是
try CodableRequest.request<T: Codable, E: ErrorResponseProtocol>(
_ method: HTTPMethod,
_ url: String,
to: T.Type,
error: E.Type,
params: [String: Any] = [String: Any](),
encoding: String = "json",
bearerToken: String = ""
)
method
和 url
是未命名的参数。to
和 error
参数是要尝试编码/解码过程的类型。params
是名称/值字典,它被转换为 form 参数或 JSON 对象,与 POST 或 PATCH 请求一起提交。encoding
将确定请求的格式是 JSON 还是 Form。bearerToken
,如果填充,将使用此 bearer token 提交 Authorization 标头。let response : HTTPbin = try CodableRequest.request(
.get,
"https://httpbin.org/get",
to: HTTPbin.self,
error: ErrorResponse.self
)
此请求的结果将是 HTTPbin
类型的对象。
let response : HTTPbin = try CodableRequest.request(
.post,
"https://httpbin.org/post",
to: HTTPbin.self,
error: ErrorResponse.self,
params: ["donkey":"kong"],
encoding: "form"
)
let response : HTTPbin = try CodableRequest.request(
.post,
"https://httpbin.org/post",
to: HTTPbin.self,
error: ErrorResponse.self,
params: ["donkey":"kong"],
encoding: "json"
)
do {
let _ : HTTPbin = try CodableRequest.request(
.post,
"https://httpbin.org/get",
to: HTTPbin.self,
error: ErrorResponse.self
)
} catch let error as ErrorResponse {
print(error.error?.code) // 405
} catch {
print(error)
}
此请求将返回 405,一种不支持的请求类型。
以下错误对象已作为响应填充
ErrorResponse(
error: Optional(codableRequest.ErrorMsg(
message: Optional("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">\n<title>405 Method Not Allowed</title>\n<h1>Method Not Allowed</h1>\n<p>The method is not allowed for the requested URL.</p>\n"),
type: Optional(""),
param: Optional(""),
code: Optional("405"))
)
)
以下结构体被测试和上述示例使用。
struct HTTPbin: Codable {
var args: [String: String]?
var data: String?
var files: [String: String]?
var form: [String: String]?
var headers: HTTPbinHeaders?
var json: [String: String]?
var origin: String?
var url: String?
}
struct HTTPbinHeaders: Codable {
var accept: String?
var acceptEncoding: String?
var acceptLanguage: String?
var connection: String?
var contentType: String?
var dnt: String?
var host: String?
var origin: String?
var referer: String?
var userAgent: String?
enum CodingKeys : String, CodingKey {
case accept = "Accept"
case acceptEncoding = "Accept-Encoding"
case acceptLanguage = "Accept-Language"
case connection = "Connection"
case contentType = "Content-Type"
case dnt = "Dnt"
case host = "Host"
case origin = "Origin"
case referer = "Referer"
case userAgent = "User-Agent"
}
}
该库正在开发中。 最初的开发是为了满足正在开发的 Stripe API 的需求。
欢迎提交 Pull 请求,如果您想讨论如何使用或如何改进,请在 Perfect Slack 频道 上联系我 - 我的句柄是 "iamjono"。
感谢 Fatih Nayebi 的启发和帮助。