HttpServer.swift 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. //
  2. // HttpServer.swift
  3. //
  4. // Created by Damian Kolakowski on 05/06/14.
  5. // Copyright (c) 2014 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. class HttpServer
  9. {
  10. typealias Handler = (String, String, Dictionary<String,String>) -> HttpResponse
  11. var handlers: [(expression: NSRegularExpression, handler: Handler)] = []
  12. var acceptSocket: CInt = -1
  13. let matchingOptions = NSMatchingOptions(0)
  14. let expressionOptions = NSRegularExpressionOptions(0)
  15. subscript (path: String) -> Handler? {
  16. get {
  17. for (expression, handler) in handlers {
  18. let numberOfMatches: Int = expression.numberOfMatchesInString(path, options: matchingOptions, range: NSMakeRange(0, path.lengthOfBytesUsingEncoding(NSASCIIStringEncoding)))
  19. if ( numberOfMatches > 0 ) {
  20. return handler
  21. }
  22. }
  23. return nil
  24. }
  25. set ( newValue ) {
  26. if let regex: NSRegularExpression = NSRegularExpression.regularExpressionWithPattern(path, options: expressionOptions, error: nil) {
  27. if let newHandler = newValue {
  28. handlers.append(expression: regex, handler: newHandler)
  29. }
  30. }
  31. }
  32. }
  33. subscript (path: String) -> String {
  34. get {
  35. return path
  36. }
  37. set ( directoryPath ) {
  38. if let regex = NSRegularExpression.regularExpressionWithPattern(path, options: expressionOptions, error: nil) {
  39. handlers.append(expression: regex, handler: { (method, path, headers) in
  40. let result = regex.firstMatchInString(path, options: self.matchingOptions, range: NSMakeRange(0, path.lengthOfBytesUsingEncoding(NSASCIIStringEncoding)))
  41. let myPath: NSString = path
  42. let filesPath = directoryPath.stringByAppendingPathComponent(myPath.substringWithRange(result.rangeAtIndex(1)))
  43. if let fileBody = String.stringWithContentsOfFile(filesPath, encoding: NSASCIIStringEncoding, error: nil) {
  44. return HttpResponse.OK(.RAW(fileBody))
  45. }
  46. return HttpResponse.NotFound
  47. })
  48. }
  49. }
  50. }
  51. func routes() -> Array<String> {
  52. var results = [String]()
  53. for (expression,_) in handlers { results.append(expression.pattern) }
  54. return results
  55. }
  56. func start(listenPort: in_port_t = 8080, error:NSErrorPointer = nil) -> Bool {
  57. releaseAcceptSocket()
  58. if let socket = Socket.tcpForListen(port: listenPort, error: error) {
  59. acceptSocket = socket
  60. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
  61. while let socket = Socket.acceptClientSocket(self.acceptSocket) {
  62. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {
  63. let parser = HttpParser()
  64. while let (path, method, headers) = parser.nextHttpRequest(socket) {
  65. let keepAlive = parser.supportsKeepAlive(headers)
  66. if let handler: Handler = self[path] {
  67. HttpServer.writeResponse(socket, response: handler(method, path, headers), keepAlive: keepAlive)
  68. } else {
  69. HttpServer.writeResponse(socket, response: HttpResponse.NotFound, keepAlive: keepAlive)
  70. }
  71. if !keepAlive { break }
  72. }
  73. Socket.release(socket)
  74. });
  75. }
  76. self.releaseAcceptSocket()
  77. });
  78. return true
  79. }
  80. return false
  81. }
  82. class func writeResponse(socket: CInt, response: HttpResponse, keepAlive: Bool) {
  83. Socket.writeStringUTF8(socket, string: "HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
  84. let messageBody = response.body()
  85. if let body = messageBody {
  86. if let nsdata = body.dataUsingEncoding(NSUTF8StringEncoding) {
  87. Socket.writeStringUTF8(socket, string: "Content-Length: \(nsdata.length)\r\n")
  88. }
  89. } else {
  90. Socket.writeStringUTF8(socket, string: "Content-Length: 0\r\n")
  91. }
  92. if keepAlive {
  93. Socket.writeStringUTF8(socket, string: "Connection: keep-alive\r\n")
  94. }
  95. //Socket.writeStringUTF8(socket, string: "Content-Type: text/html; charset=UTF-8\r\n")
  96. for (name, value) in response.headers() {
  97. Socket.writeStringUTF8(socket, string: "\(name): \(value)\r\n")
  98. }
  99. Socket.writeStringUTF8(socket, string: "\r\n")
  100. if let body = messageBody {
  101. Socket.writeStringUTF8(socket, string: body)
  102. }
  103. }
  104. func stop() {
  105. releaseAcceptSocket()
  106. }
  107. func releaseAcceptSocket() {
  108. if ( acceptSocket != -1 ) {
  109. Socket.release(acceptSocket)
  110. acceptSocket = -1
  111. }
  112. }
  113. }