Use URLSession and DispatchSemaphore to create custom implementation of status API
This commit is contained in:
parent
c5d4d82c42
commit
362f68108c
@ -5,7 +5,7 @@
|
||||
"Node 1": [
|
||||
{
|
||||
"name": "Example",
|
||||
"url": "https://example.com",
|
||||
"url": "https://example.comd",
|
||||
"description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
|
||||
}
|
||||
],
|
||||
|
@ -1,7 +0,0 @@
|
||||
import Foundation
|
||||
import Vapor
|
||||
|
||||
struct isItUp: Codable {
|
||||
let isitdown: Bool
|
||||
let response_code: Int
|
||||
}
|
@ -1,5 +1,6 @@
|
||||
import Vapor
|
||||
import Foundation
|
||||
import FoundationNetworking
|
||||
import Crypto
|
||||
import Leaf
|
||||
|
||||
@ -13,13 +14,21 @@ func routes(_ app: Application) throws {
|
||||
return req.view.render("home", LContext(config: config, loggedIn: loginBool))
|
||||
}
|
||||
|
||||
app.get("status", ":url") { req -> EventLoopFuture<[String: String]> in
|
||||
let url = URL(string: req.parameters.get("url")!)
|
||||
return req.client.get("https://isitdown.site/api/v3/\(url!)").flatMapThrowing { res in
|
||||
try res.content.decode(isItUp.self)
|
||||
}.map { json in
|
||||
["down": String(json.isitdown), "code": String(json.response_code)]
|
||||
}
|
||||
app.get("status", ":url") { req -> [String: String] in
|
||||
let url = URL(string: "http://\(req.parameters.get("url")!)")
|
||||
var statusDict: [String:String] = [:]
|
||||
var headReq = URLRequest(url: url!)
|
||||
headReq.httpMethod = "HEAD"
|
||||
let semaphore = DispatchSemaphore(value: 0)
|
||||
URLSession.shared.dataTask(with: headReq, completionHandler: { (_, response, error) in
|
||||
if let httpURLResponse = response as? HTTPURLResponse {
|
||||
statusDict["code"] = String(httpURLResponse.statusCode)
|
||||
statusDict["down"] = httpURLResponse.statusCode != 200 ? "true" : "false"
|
||||
}
|
||||
semaphore.signal()
|
||||
}).resume()
|
||||
semaphore.wait()
|
||||
return statusDict.count > 0 ? statusDict : ["code": "0", "down": "true"]
|
||||
}
|
||||
|
||||
app.get("login") { req -> EventLoopFuture<View> in
|
||||
|
Reference in New Issue
Block a user