/
main.swift
executable file
·55 lines (48 loc) · 1.34 KB
/
main.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/swift sh
import Macro // @Macro-swift
import Foundation
http.createServer { req, res in
// log request
req.log.log("\(req.method) \(req.url)")
guard req.method != "CONNECT" else {
req.log.error("Connect not supported.")
res.writeHead(501)
res.end()
return
}
guard let url = URL(string: req.url),
let scheme = url.scheme, let host = url.host else
{
req.log.error("Invalid URL:", req.url)
res.writeHead(400)
res.end()
return
}
let options = http.ClientRequestOptions(
headers : req.headers, // TODO: Add 'Via' and such, drop the proper ones
protocol : "\(scheme):",
host : host,
method : req.method,
path : url.path
)
let proxiedRequest = http.request(options) { proxiedResponse in
res.writeHead(proxiedResponse.status,
headers: proxiedResponse.headers)
// send proxied response body to the original client
proxiedResponse
.pipe(res)
.onError { error in
req.log.error("proxy response delivery failed:", error)
}
}
.onError { error in
req.log.error("proxy request delivery failed:", error)
res.writeHead(500)
res.end()
}
// Send the request body to the target server
req.pipe(proxiedRequest)
}
.listen(1337) { server in
server.log.log("Server listening on http://0.0.0.0:1337/")
}