Server-side Swiftを作ってみます。
- カッコいい感じで書いてますがCGIです...
環境変数さえ取れればCGIはできますよね。
- さらっと書いてみます。
- ポイントは
NSProcessInfo.processInfo().environment
だけです。簡単そうですね。
printenv.swift
import Foundation
class CGI {
var p = [String:String]()
init() {
// プロセスの環境変数を取得
let ENV = NSProcessInfo.processInfo().environment
// 環境変数からQUERY_STRINGを取得
if let params = ENV["QUERY_STRING"] {
params.componentsSeparatedByString("&").forEach {
let kv = $0.componentsSeparatedByString("=")
p[kv[0]] = kv[1]
}
}
}
func param(key:String) -> String {
if let ret = p[key] {
return ret
} else {
return ""
}
}
}
let q = CGI()
print("Content-type: text/html; charset=utf-8\n")
print("<!DOCTYPE html>")
print("<html lang=\"ja\">")
print("<head>")
print("<meta charset=\"UTF-8\">")
print("<meta name=\"viewport\" content=\"width=device-width\">")
print("<title>Hello Swift</title>")
print("</head>")
print("<body>")
print("<h4>Request Parameter</h4>")
print("<p>name : \(q.param("name"))</p>")
print("<p>age : \(q.param("age"))</p>")
print("</body>")
print("</html>")
- printenv.cgiでswiftcでビルドしてください。
printenv.cgi
- 出来上がったprintenv.cgiをcgi-bin以下に置いてください。
- それで
http://localhost/cgi-bin/printenv.cgi?name=Qiita&age=123
にアクセスすると...
- できましたー
apache benchを取ってみる
- ま、プロセス起動になるんですけどどんなもんでしょうか?
ab結果
# ab -n 1000 -c 10 "http://localhost/cgi-bin/printenv.cgi?name=Qiita&age=123"
Server Software: Apache/2.4.16
Server Hostname: localhost
Server Port: 80
Document Path: /cgi-bin/printenv.cgi?name=Qiita&age=123
Document Length: 238 bytes
Concurrency Level: 10
Time taken for tests: 5.110 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 392009 bytes
HTML transferred: 238000 bytes
Requests per second: 195.68 [#/sec] (mean)
Time per request: 51.104 [ms] (mean)
Time per request: 5.110 [ms] (mean, across all concurrent requests)
Transfer rate: 74.91 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.4 0 9
Processing: 15 50 12.9 49 145
Waiting: 14 50 12.6 48 144
Total: 15 51 12.9 49 145
- 似たようなperl-cgiがあるのでそれでも試してみます。
ab結果
Server Software: Apache/2.4.16
Server Hostname: localhost
Server Port: 80
Document Path: /cgi-bin/env.cgi?name=Qiita&age=123
Document Length: 736 bytes
Concurrency Level: 10
Time taken for tests: 3.631 seconds
Complete requests: 1000
Failed requests: 0
Total transferred: 877227 bytes
HTML transferred: 736000 bytes
Requests per second: 275.43 [#/sec] (mean)
Time per request: 36.307 [ms] (mean)
Time per request: 3.631 [ms] (mean, across all concurrent requests)
Transfer rate: 235.95 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.5 0 6
Processing: 12 36 18.9 33 341
Waiting: 11 33 11.3 32 340
Total: 12 36 18.9 33 342
- perlより全然遅いやんけ〜〜〜
まとめ
- swiftをcgiで使うのはやめましょう