/*** Swift can say hello to your browser! Requirements ------------ * OSX Yosemite or newer * Xcode 7, Swift 2 * Homebrew ** packages: fastcgi, fcgi-swpawn, nginx packages Make it work ------------ # Download and compile the code swiftc -sdk /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk fcgi_app.swift -o fcgi_app # Configure Nginx front-end --- ... --- ... --- ... --- ... --- location /swift { root /usr/local/var/www/; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.html; fastcgi_param SCRIPT_FILENAME /cgi-bin/fcgi$fastcgi_script_name; include fastcgi_params; } --- ... --- ... --- ... --- ... --- # Spawn your web app as a FCGI daemon --- ... --- ... --- ... --- ... --- /usr/local/bin/spawn-fcgi \ -a 127.0.0.1 -p 9000 \ -u segabor -g staff \ -f ./fcgi_app \ -P ./fcgi_app.pid --- ... --- ... --- ... --- ... --- # Open your browser and enjoy the result http://localhost/swift/hello ***/ import Darwin // // The ugly part -- attach fastcgi library // let handle = dlopen( "/usr/local/Cellar/fcgi/2.4.0/lib/libfcgi.dylib", RTLD_NOW) let sym = dlsym(handle, "FCGI_Accept") // lookup fcgi functions and map them to Swift types // typealias FCGI_Accept_T = @convention(c) (Void)->CInt let FCGI_Accept : ()->CInt = unsafeBitCast(sym, FCGI_Accept_T.self) let sym3 = dlsym(handle, "FCGI_puts") typealias FCGI_Puts_T = @convention(c) (UnsafeMutablePointer)->CInt let FCGI_puts : FCGI_Puts_T = unsafeBitCast(sym3, FCGI_Puts_T.self) // // Let the fun begin // var r = FCGI_Accept() while r >= 0 { let str = "Content-type: text/html\r\n" + "\r\n" + "Hello World" + "

FastCGI Hello! (Swift, fcgi_stdio library)

" + "\r\n" FCGI_puts( UnsafeMutablePointer( str.utf8.map { CChar(bitPattern: $0) } ) ) r = FCGI_Accept() } dlclose(handle)