@@ -23,59 +23,15 @@ public class HttpParser {
2323 }
2424 let request = HttpRequest ( )
2525 request . method = statusLineTokens [ 0 ]
26- request . path = statusLineTokens [ 1 ]
27- request . queryParams = extractQueryParams ( request . path )
26+ let urlComponents = URLComponents ( string : statusLineTokens [ 1 ] )
27+ request . path = urlComponents ? . path ?? " "
28+ request . queryParams = urlComponents ? . queryItems ? . map { ( $0 . name , $0 . value ?? " " ) } ?? [ ]
2829 request . headers = try readHeaders ( socket )
2930 if let contentLength = request . headers [ " content-length " ] , let contentLengthValue = Int ( contentLength ) {
3031 request . body = try readBody ( socket , size : contentLengthValue )
3132 }
3233 return request
33- }
34-
35- private func extractQueryParams ( _ url : String ) -> [ ( String , String ) ] {
36- #if compiler( >= 5 . 0 )
37- guard let questionMarkIndex = url . firstIndex ( of : " ? " ) else {
38- return [ ]
39- }
40- #else
41- guard let questionMarkIndex = url . index ( of : " ? " ) else {
42- return [ ]
43- }
44- #endif
45- let queryStart = url . index ( after : questionMarkIndex )
46-
47- guard url . endIndex > queryStart else { return [ ] }
48-
49- #if swift( >= 4 . 0 )
50- let query = String ( url [ queryStart ..< url . endIndex ] )
51- #else
52- guard let query = String ( url [ queryStart ..< url . endIndex ] ) else { return [ ] }
53- #endif
54-
55- return query . components ( separatedBy : " & " )
56- . reduce ( [ ( String , String ) ] ( ) ) { ( result , stringValue ) -> [ ( String , String ) ] in
57- #if compiler( >= 5 . 0 )
58- guard let nameEndIndex = stringValue . firstIndex ( of : " = " ) else {
59- return result
60- }
61- #else
62- guard let nameEndIndex = stringValue . index ( of : " = " ) else {
63- return result
64- }
65- #endif
66- guard let name = String ( stringValue [ stringValue . startIndex ..< nameEndIndex ] ) . removingPercentEncoding else {
67- return result
68- }
69- let valueStartIndex = stringValue . index ( nameEndIndex , offsetBy : 1 )
70- guard valueStartIndex < stringValue . endIndex else {
71- return result + [ ( name , " " ) ]
72- }
73- guard let value = String ( stringValue [ valueStartIndex ..< stringValue . endIndex ] ) . removingPercentEncoding else {
74- return result + [ ( name , " " ) ]
75- }
76- return result + [ ( name , value ) ]
7734 }
78- }
7935
8036 private func readBody ( _ socket : Socket , size : Int ) throws -> [ UInt8 ] {
8137 return try socket . read ( length : size )
0 commit comments