1 module hunt.imf.protocol.http.HttpEncoder; 2 3 import hunt.net.codec.Encoder; 4 import hunt.net.Connection; 5 import hunt.imf.ParserBase; 6 import hunt.imf.MessageBuffer; 7 import hunt.collection.ByteBuffer; 8 import hunt.collection.BufferUtils; 9 import hunt.Exceptions; 10 import std.bitmanip; 11 import hunt.util.Serialize; 12 import std.conv; 13 import std.stdio; 14 import std.format; 15 import std.array; 16 import std.uri; 17 18 class HttpEncoder : ParserBase , Encoder { 19 20 this() { 21 } 22 23 override void encode(Object message, Connection connection) 24 { 25 auto msg = cast(MessageBuffer)message; 26 HttpContent content= unserialize!HttpContent(cast(byte[])msg.message); 27 content.headField[Field.CONTENTLENGTH] = to!string(content.body.length); 28 auto appender = appender!string; 29 appender.reserve(1024); 30 if (content.path.length != 0) 31 { 32 appender.put(content.method); 33 appender.put(" "); 34 appender.put(generateUrl(content)); 35 appender.put(" HTTP/1.1"); 36 appender.put(LINEFEEDS); 37 appender.put(generateHeadField(content)); 38 } 39 else 40 { 41 appender.put("HTTP/1.1 "); 42 appender.put(to!string(content.status)); 43 appender.put(LINEFEEDS); 44 appender.put(generateHeadField(content)); 45 } 46 appender.put(content.body); 47 // writefln(appender[]); 48 connection.write(appender[]); 49 } 50 51 void setBufferSize(int size) 52 { 53 54 } 55 56 string generateUrl(ref HttpContent content) 57 { 58 auto appender = appender!string; 59 appender.reserve(1024); 60 61 appender.put(content.path); 62 if (content.parameters.length != 0) 63 { 64 appender.put("?"); 65 } 66 bool begin = true; 67 foreach (key ; content.parameters.keys) 68 { 69 if (begin) 70 { 71 begin = !begin; 72 } 73 else 74 { 75 appender.put("&"); 76 } 77 78 appender.put(key); 79 appender.put("="); 80 appender.put(content.parameters[key]); 81 } 82 return encodeComponent(appender[]); 83 } 84 85 string generateHeadField (ref HttpContent content) 86 { 87 auto appender = appender!string; 88 foreach (key ; content.headField.keys) 89 { 90 appender.put(key); 91 appender.put(": "); 92 appender.put(content.headField[key]); 93 appender.put(LINEFEEDS); 94 } 95 appender.put(content.headField.length == 0?HTTPHEADEOF:LINEFEEDS); 96 return appender[]; 97 } 98 } 99