1919using System ;
2020using System . Collections . Generic ;
2121using System . IO ;
22+ using System . Threading . Tasks ;
2223
2324namespace uhttpsharp
2425{
2526 public sealed class HttpRequest
2627 {
28+ public static async Task < HttpRequest > Build ( Stream stream )
29+ {
30+ var retVal = new HttpRequest ( stream ) ;
31+ await retVal . Process ( ) ;
32+
33+ return retVal ;
34+ }
35+
2736 public bool Valid { get ; private set ; }
2837 public Dictionary < string , string > Headers { get ; private set ; }
2938 public HttpMethod HttpMethod { get ; private set ; }
@@ -33,20 +42,21 @@ public sealed class HttpRequest
3342 public HttpRequestParameters Parameters { get ; private set ; }
3443
3544 private readonly Stream _stream ;
45+ private readonly StreamReader _streamReader ;
3646
3747 public HttpRequest ( Stream stream )
3848 {
3949 Headers = new Dictionary < string , string > ( ) ;
4050 _stream = stream ;
41- Process ( ) ;
51+ _streamReader = new StreamReader ( _stream ) ;
4252 }
4353
44- private void Process ( )
54+ private async Task Process ( )
4555 {
4656 Valid = false ;
4757
4858 // parse the http request
49- var request = ReadLine ( ) ;
59+ var request = await _streamReader . ReadLineAsync ( ) ;
5060 if ( request == null )
5161 return ;
5262 var tokens = request . Split ( ' ' ) ;
@@ -69,43 +79,30 @@ private void Process()
6979
7080 HttpProtocol = tokens [ 2 ] ;
7181 URL = tokens [ 1 ] ;
72- Uri = new Uri ( "http://" + HttpServer . Instance . Address + "/" + URL . TrimStart ( '/' ) ) ;
82+ Uri = new Uri ( URL , UriKind . Relative ) ;
83+
7384 Parameters = new HttpRequestParameters ( URL ) ;
7485
75- Console . WriteLine ( string . Format ( "[{0}:{1}] URL: {2}" , HttpProtocol , HttpMethod , URL ) ) ;
86+ Console . WriteLine ( "[{0}:{1}] URL: {2}" , HttpProtocol , HttpMethod , URL ) ;
7687
7788 // get the headers
7889 string line ;
79- while ( ( line = ReadLine ( ) ) != null )
90+ while ( ( line = await _streamReader . ReadLineAsync ( ) ) != null )
8091 {
81- if ( line . Equals ( "" ) ) break ;
92+ if ( line . Equals ( string . Empty ) ) break ;
8293 var keys = line . Split ( ':' ) ;
8394 Headers . Add ( keys [ 0 ] , keys [ 1 ] ) ;
8495 }
8596
8697 Valid = true ;
8798 }
8899
89- private string ReadLine ( )
100+ private KeyValuePair < string , string > SplitHeader ( string header )
90101 {
91- var buffer = string . Empty ;
92-
93- while ( true )
94- {
95- var _char = _stream . ReadByte ( ) ;
96- if ( _char == '\n ' ) break ;
97- if ( _char == '\r ' ) continue ;
98- if ( _char == - 1 )
99- {
100- if ( buffer != string . Empty )
101- return buffer ;
102- return null ;
103- }
104- buffer += Convert . ToChar ( _char ) ;
105- }
106-
107- return buffer ;
102+ var index = header . IndexOf ( ':' ) ;
103+ return new KeyValuePair < string , string > ( header . Substring ( 0 , index ) , header . Substring ( index + 1 ) ) ;
108104 }
105+
109106 }
110107
111108 public enum HttpMethod
0 commit comments