HttpParser.swift 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // HttpParser.swift
  3. // Swifter
  4. //
  5. // Copyright (c) 2014-2016 Damian Kołakowski. All rights reserved.
  6. //
  7. import Foundation
  8. enum HttpParserError: Error {
  9. case InvalidStatusLine(String)
  10. }
  11. public class HttpParser {
  12. public init() { }
  13. public func readHttpRequest(_ socket: Socket) throws -> HttpRequest {
  14. let statusLine = try socket.readLine()
  15. let statusLineTokens = statusLine.split(" ")
  16. if statusLineTokens.count < 3 {
  17. throw HttpParserError.InvalidStatusLine(statusLine)
  18. }
  19. let request = HttpRequest()
  20. request.method = statusLineTokens[0]
  21. request.path = statusLineTokens[1]
  22. request.queryParams = extractQueryParams(request.path)
  23. request.headers = try readHeaders(socket)
  24. if let contentLength = request.headers["content-length"], let contentLengthValue = Int(contentLength) {
  25. request.body = try readBody(socket, size: contentLengthValue)
  26. }
  27. return request
  28. }
  29. private func extractQueryParams(_ url: String) -> [(String, String)] {
  30. guard let query = url.split("?").last else {
  31. return []
  32. }
  33. return query.split("&").reduce([(String, String)]()) { (c, s) -> [(String, String)] in
  34. let tokens = s.split(1, separator: "=")
  35. if let name = tokens.first?.removingPercentEncoding, let value = tokens.last?.removingPercentEncoding {
  36. return c + [(name, value)]
  37. }
  38. return c
  39. }
  40. }
  41. private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] {
  42. var body = [UInt8]()
  43. for _ in 0..<size { body.append(try socket.read()) }
  44. return body
  45. }
  46. private func readHeaders(_ socket: Socket) throws -> [String: String] {
  47. var headers = [String: String]()
  48. while case let headerLine = try socket.readLine() , !headerLine.isEmpty {
  49. let headerTokens = headerLine.split(1, separator: ":")
  50. if let name = headerTokens.first, let value = headerTokens.last {
  51. headers[name.lowercased()] = value.trim()
  52. }
  53. }
  54. return headers
  55. }
  56. func supportsKeepAlive(_ headers: [String: String]) -> Bool {
  57. if let value = headers["connection"] {
  58. return "keep-alive" == value.trim()
  59. }
  60. return false
  61. }
  62. }