HttpParser.swift 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.components(separatedBy: " ")
  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. let tokens = url.components(separatedBy: "?")
  31. guard let query = tokens.last, tokens.count >= 2 else {
  32. return []
  33. }
  34. return query.components(separatedBy: "&").reduce([(String, String)]()) { (c, s) -> [(String, String)] in
  35. let tokens = s.components(separatedBy: "=")
  36. let name = tokens.first?.removingPercentEncoding
  37. let value = tokens.count > 1 ? (tokens.last?.removingPercentEncoding ?? "") : ""
  38. if let nameFound = name {
  39. return c + [(nameFound, value)]
  40. }
  41. return c
  42. }
  43. }
  44. private func readBody(_ socket: Socket, size: Int) throws -> [UInt8] {
  45. var body = [UInt8]()
  46. for _ in 0..<size { body.append(try socket.read()) }
  47. return body
  48. }
  49. private func readHeaders(_ socket: Socket) throws -> [String: String] {
  50. var headers = [String: String]()
  51. while case let headerLine = try socket.readLine() , !headerLine.isEmpty {
  52. let headerTokens = headerLine.components(separatedBy: ":")
  53. if let name = headerTokens.first, let value = headerTokens.last {
  54. headers[name.lowercased()] = value.trimmingCharacters(in: .whitespaces)
  55. }
  56. }
  57. return headers
  58. }
  59. func supportsKeepAlive(_ headers: [String: String]) -> Bool {
  60. if let value = headers["connection"] {
  61. return "keep-alive" == value.trimmingCharacters(in: .whitespaces)
  62. }
  63. return false
  64. }
  65. }