1 /* 2 * Archttp - A highly performant web framework written in D. 3 * 4 * Copyright (C) 2021-2022 Kerisy.com 5 * 6 * Website: https://www.kerisy.com 7 * 8 * Licensed under the Apache-2.0 License. 9 * 10 */ 11 12 module archttp.HttpContext; 13 14 import archttp.HttpRequest; 15 import archttp.HttpResponse; 16 import archttp.HttpRequestHandler; 17 18 import nbuff; 19 20 import geario.net.TcpStream; 21 import geario.codec.Framed; 22 import geario.logging; 23 24 alias Framed!(HttpRequest, HttpResponse) HttpFramed; 25 26 class HttpContext 27 { 28 private HttpRequest _request; 29 private HttpResponse _response; 30 private TcpStream _connection; 31 private HttpFramed _framed; 32 private bool _keepAlive; 33 private bool _keepAliveSetted; 34 35 this(TcpStream connection, HttpFramed framed) 36 { 37 _connection = connection; 38 _framed = framed; 39 } 40 41 HttpRequest request() { 42 return _request; 43 } 44 45 void request(HttpRequest request) 46 { 47 _request = request; 48 _request.context(this); 49 50 initKeepAliveValue(); 51 } 52 53 HttpResponse response() 54 { 55 if (_response is null) 56 _response = new HttpResponse(this); 57 58 return _response; 59 } 60 61 void response(HttpResponse response) 62 { 63 _response = response; 64 } 65 66 TcpStream connection() 67 { 68 return _connection; 69 } 70 71 bool keepAlive() 72 { 73 return _keepAlive; 74 } 75 76 private void initKeepAliveValue() 77 { 78 if (false == _keepAliveSetted) 79 { 80 string connectionType = _request.header("Connection"); 81 if (connectionType.length && connectionType == "keep-alive") 82 _keepAlive = true; 83 else 84 _keepAlive = false; 85 86 _keepAliveSetted = true; 87 } 88 } 89 90 void Write(string data) 91 { 92 _connection.Write(cast(ubyte[])data); 93 } 94 95 void Write(NbuffChunk bytes) 96 { 97 _connection.Write(bytes); 98 } 99 100 void Send(HttpResponse response) 101 { 102 _framed.Send(response); 103 } 104 105 void End() 106 { 107 _connection.Close(); 108 } 109 }