Skip to content

Instantly share code, notes, and snippets.

@kjessup
Created December 2, 2016 19:45
Show Gist options
  • Save kjessup/7dcb22a576295bde3ac5215121997499 to your computer and use it in GitHub Desktop.
Save kjessup/7dcb22a576295bde3ac5215121997499 to your computer and use it in GitHub Desktop.
import PerfectCURL
let urls = ["http://localhost:8080/a", "http://localhost:8080/b", "http://localhost:8080/c", "http://localhost:8080/d"]
func fetchURLS(_ urls: [String], process: (_ url: String, _ headers: String?, _ body: String?) -> ()) {
struct curlTrack {
let url: String
let curl: CURL
var done = false
var headers = [UInt8]()
var body = [UInt8]()
init(url: String) {
self.url = url
self.curl = CURL(url: url)
}
}
var tracker = urls.map { curlTrack(url: $0) }
while !tracker.isEmpty {
tracker = tracker.map {
var ret = $0
let (go, _, h, b) = $0.curl.perform()
ret.headers.append(contentsOf: h ?? [])
ret.body.append(contentsOf: b ?? [])
ret.done = !go
return ret
}.filter {
guard $0.done else {
return true
}
let head = ($0.headers + [0 as UInt8]).map { Int8($0) }
let body = ($0.body + [0 as UInt8]).map { Int8($0) }
process($0.url, String(validatingUTF8: head), String(validatingUTF8: body))
return false
}
}
}
fetchURLS(urls) {
url, headers, body in
print("Completed URL \(url) \(body ?? "")")
}
print("done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment