Skip to content

Instantly share code, notes, and snippets.

@segabor
Last active September 25, 2015 06:32
Show Gist options
  • Save segabor/362d53f049d42d50eb81 to your computer and use it in GitHub Desktop.
Save segabor/362d53f049d42d50eb81 to your computer and use it in GitHub Desktop.
A simple FastCGI PoC written in Swift
/***
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<CChar>)->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" +
"<!DOCTYPE html><html><head><title>Hello World</title></head><body>" +
"<h1>FastCGI Hello! (Swift, fcgi_stdio library)</h1></body></html>" +
"\r\n"
FCGI_puts( UnsafeMutablePointer<CChar>( str.utf8.map { CChar(bitPattern: $0) } ) )
r = FCGI_Accept()
}
dlclose(handle)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment