mod_swift is a technology demo which shows how to write native modules for the Apache Web Server in the Swift programming language.

Server Side Swift the right way.

It works out of the box on macOS 10.11+ with Xcode 8 and the builtin system Apache (no Apache install required!), with the Homebrew Apache 2.4 on macOS (brew install homebrew/apache/httpd24), and on Linux (tested with Ubuntu 16.04).

Shows us some code!

We provide a few examples: a 'raw' Apache Module, a demo for the bundled Express, as well as a TodoMVC backend. But here you go, the "standard" Node example, a HelloWorld webpage:

func expressMain() {
  apache.onRequest { req, res in
    res.writeHead(200, [ "Content-Type": "text/html" ])
    try res.end("<h1>Hello World</h1>")
  }
}

Middleware using Express features like Mustache templates or JSON support:

let app = apache.express(bodyParser.urlencoded(), 
                         cookieParser(), session())
  
app.get("/express/cookies") { req, res, _ in
  try res.json(req.cookies)  // returns all cookies as JSON
}

app.get("/express/") { req, res, _ in
  let tagline = arc4random_uniform(taglines.count)

  let values : [ String : Any ] = [
    "tagline"     : taglines[tagline],
    "viewCount"   : req.session["viewCount"] ?? 0,
    "cowOfTheDay" : cows.vaca()
  ]
  try res.render("index", values)
}

Access a SQL database using Apache mod_dbd:

guard let con = req.dbdAcquire()                 else { return ... }
guard let res = con.select("SELECT * FROM pets") else { return ... }

while let row = res.next() {
  req.puts("<li>\(row[0])</li>")
}