From 362f68108c50cd6fddd742b9076cbe09677f4946 Mon Sep 17 00:00:00 2001 From: Arsen Musayelyan Date: Sun, 15 Nov 2020 01:34:52 -0800 Subject: [PATCH] Use URLSession and DispatchSemaphore to create custom implementation of status API --- Resources/config.json | 2 +- Sources/App/isItUp.swift | 7 ------- Sources/App/routes.swift | 23 ++++++++++++++++------- 3 files changed, 17 insertions(+), 15 deletions(-) delete mode 100644 Sources/App/isItUp.swift diff --git a/Resources/config.json b/Resources/config.json index 9beffaf..b889d51 100644 --- a/Resources/config.json +++ b/Resources/config.json @@ -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." } ], diff --git a/Sources/App/isItUp.swift b/Sources/App/isItUp.swift deleted file mode 100644 index b370b4d..0000000 --- a/Sources/App/isItUp.swift +++ /dev/null @@ -1,7 +0,0 @@ -import Foundation -import Vapor - -struct isItUp: Codable { - let isitdown: Bool - let response_code: Int -} \ No newline at end of file diff --git a/Sources/App/routes.swift b/Sources/App/routes.swift index f221ccb..2a8ab23 100644 --- a/Sources/App/routes.swift +++ b/Sources/App/routes.swift @@ -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 in