1 module hunt.http.codec.http.stream.HttpOutputStream; 2 3 import hunt.http.codec.http.model.HttpHeader; 4 import hunt.http.codec.http.model.MetaData; 5 6 import hunt.container; 7 import hunt.io; 8 import hunt.lang.exception; 9 import hunt.logging; 10 import std.conv; 11 12 abstract class HttpOutputStream : OutputStream { 13 14 protected bool clientMode; 15 protected MetaData metaData; 16 protected bool closed; 17 protected bool committed; 18 19 this(MetaData metaData, bool clientMode) { 20 this.metaData = metaData; 21 this.clientMode = clientMode; 22 } 23 24 bool isClosed() { 25 return closed; 26 } 27 28 bool isCommitted() { 29 return committed; 30 } 31 32 override 33 void write(int b) { 34 // byte* ptr = cast(byte*)&b; 35 // write(ptr[0..int.sizeof]); 36 37 write(cast(byte[]) [cast (byte) b]); 38 } 39 40 override 41 void write(byte[] array, int offset, int length) { 42 assert(array !is null, "The data must be not null"); 43 write(ByteBuffer.wrap(array, offset, length)); 44 } 45 46 alias write = OutputStream.write; 47 48 // void writeWithContentLength(Collection!ByteBuffer data) { 49 // if (closed) { 50 // return; 51 // } 52 53 // try { 54 // if (!committed) { 55 // long contentLength = BufferUtils.remaining(data); 56 // metaData.getFields().put(HttpHeader.CONTENT_LENGTH, contentLength.to!string); 57 // } 58 // foreach (ByteBuffer buf ; data) { 59 // write(buf); 60 // } 61 // } finally { 62 // close(); 63 // } 64 // } 65 66 void writeWithContentLength(ByteBuffer[] data) { 67 if (closed) { 68 return; 69 } 70 71 try { 72 if (!committed) { 73 long contentLength = BufferUtils.remaining(data); 74 metaData.getFields().put(HttpHeader.CONTENT_LENGTH, contentLength.to!string); 75 } 76 foreach (ByteBuffer buf ; data) { 77 write(buf); 78 } 79 } finally { 80 close(); 81 } 82 } 83 84 void writeWithContentLength(ByteBuffer data) { 85 writeWithContentLength([data]); 86 } 87 88 abstract void commit() ; 89 90 abstract void write(ByteBuffer data) ; 91 }