water_http 4.0.3

fast web http framework that support http 1 and http 2 with very easy use
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
mod writer;
mod sender;
mod file_response;


pub use file_response::*;
pub use writer::*;
pub use sender::*;
#[cfg(feature = "lazy_response")]
use crate::http::status_code::HttpStatusCode;
#[cfg(feature = "lazy_response")]
use std::collections::HashMap;
#[cfg(feature = "lazy_response")]
use bytes::Bytes;
#[cfg(feature = "lazy_response")]
use serde::{Serialize};
#[cfg(feature = "lazy_response")]
/// # LazyResponse Framework Component
///
/// This module provides a heap-allocated, mutable HTTP response builder designed
/// for fast, custom lifecycle management within the framework.
///
/// ### Middleware and Pipeline Architecture
/// Because responses often need to be inspected, altered, or augmented by downstream
/// response middleware (e.g., adding security headers, logging, compression, or session management)
/// *before* final serialization, `LazyResponse` holds the response states temporarily in the heap.
/// This deferred execution (lazy writing) prevents writing data prematurely to the network socket.

/// A heap-allocated container representing an inflight HTTP response.
///
/// It acts as a staging area, allowing the core application logic to set data,
/// and subsequently allowing response middleware to intercept and mutate status, headers,
/// or body payloads before network transmission.
pub struct LazyResponse {
    pub http_status_code: HttpStatusCode<'static>,
    /// headers map for response
    pub headers:HashMap<String,String>,
    pub response_data:Bytes
}

#[cfg(feature = "lazy_response")]

impl LazyResponse {

    pub fn new()->Self{
        let mut headers = HashMap::new();
        let date = httpdate::fmt_http_date(std::time::SystemTime::now());
        headers.insert("DATE".into(),date);
        LazyResponse {
            http_status_code:HttpStatusCode::OK,
            headers,
            response_data:Bytes::new()
        }
    }

    /// sending normal plain text response
    pub fn set_text_response(&mut self,data:&str){
        self.headers.insert("Content-Type".into(),"text/plain; charset=utf-8".into());
        self.headers.insert("Content-Length".to_string(),data.len().to_string());
        self.response_data = Bytes::from(data.as_bytes().to_vec());
    }

    /// setting status code
    pub fn set_status_code(&mut self,s:HttpStatusCode<'static>){
        self.http_status_code = s;
    }

    /// setting single header
    pub fn set_header(&mut self,k:impl ToString,v:impl ToString){
        self.headers.insert(k.to_string(),v.to_string());
    }

    /// setting the whole headers including date and all custom headers
    pub fn set_all_headers(&mut self,headers:HashMap<String,String>){
        self.headers = headers;
    }

    /// sending normal plain text response
    pub fn set_json_response(&mut self,data:impl Serialize)->Result<(),()>{
        let data = serde_json::to_vec(&data)
            .map_err(|_| ())?;
        self.headers.insert("Content-Type".into(),"application/json".into());
        self.headers.insert("Content-Length".to_string(),data.len().to_string());
        self.response_data = Bytes::from(data);
        Ok(())
    }


    /// set custom response data
    pub fn set_custom_response_data(&mut self,data:Bytes){
        self.response_data = data;
    }
}




//
// #[doc(hidden)]
// pub struct HeaderResponseBuilder {
//       first_line: FirstLine,
//       data:Vec<u8>,
// }
// impl HeaderResponseBuilder {
//
//
//     pub fn custom(
//         first_line: FirstLine)->Self
//     {
//         let  data = Vec::with_capacity(1024);
//         Self {
//             first_line,
//             data
//         }
//     }
//
//
//     pub fn to_bytes(&self)->Vec<u8>{
//         let mut f = self.first_line.to_bytes();
//         f.extend_from_slice(&self.data);
//         f.extend_from_slice(b"\r\n");
//         f
//     }
//     pub fn set_header_key_value(&mut self,key:impl std::fmt::Display,value:impl std::fmt::Display){
//         self.data
//             .extend_from_slice(
//                 format!("{key}: {value}\r\n").as_bytes()
//             );
//     }
//     /// creating headers with switch protocols message
//     pub fn switching_protocols_headers()->Self{
//         Self::custom(
//             FirstLine {
//                 http_version: HttpVersion::Http1,
//                 status: HttpStatus {
//                     code: 101,
//                     value: "Switching Protocols".to_string()
//                 }
//             }
//         )
//     }
//
//     /// creating headers that said using http2 is required
//     pub fn required_h2_protocol_headers()->Self{
//         Self::custom(
//             FirstLine {
//                 http_version: HttpVersion::Http1,
//                 status: HttpStatus {
//                     code: 426,
//                     value: "Upgrade Required".to_string()
//                 }
//             }
//         )
//     }
//
//
//     /// creating temporary redirect header with status code 307 (Internal Redirect)
//     pub fn temporary_redirect_header(url:&str)->Self{
//         let mut headers =  Self::custom(
//             FirstLine {
//                 http_version: HttpVersion::Http1,
//                 status: HttpStatus {
//                     code: 307,
//                     value: "Internal Redirect".to_string()
//                 }
//             }
//         );
//         headers.set_header_key_value("Location",url);
//         headers
//     }
//
//     /// Creating permanent Redirect header with status code 301 (Permanently Redirect)
//     pub fn permanent_redirect_header(url:&str)->Self{
//         let mut headers =  Self::custom(
//             FirstLine {
//                 http_version: HttpVersion::Http1,
//                 status: HttpStatus {
//                     code: 301,
//                     value: "Permanently Redirect".to_string()
//                 }
//             }
//         );
//         headers.set_header_key_value("Location",url);
//         headers
//     }
//
//
//     /// creating found redirect header with status code 302 (Found Redirect)
//     pub fn found_redirect_header(url:&str)->Self{
//         let mut headers =  Self::custom(
//             FirstLine {
//                 http_version: HttpVersion::Http1,
//                 status: HttpStatus {
//                     code: 302,
//                     value: "Found Redirect".to_string()
//                 }
//             }
//         );
//         headers.set_header_key_value("Location",url);
//         headers
//     }
//
//     /// Creating `ResponseHeadersBuilder` with requiring http2 to be the used protocol
//     pub fn required_h2()->Self {
//         let mut headers = Self::required_h2_protocol_headers();
//         headers.set_header_key_value("connection","Upgrade");
//         headers.set_header_key_value("Upgrade","h2c");
//         headers
//     }
//
//     /// Creating headers that tells the client to switch to http2 protocol
//     pub fn switch_to_h2c_headers()->Self {
//         let mut headers = Self::switching_protocols_headers();
//         headers.set_header_key_value("connection","Upgrade");
//         headers.set_header_key_value("Upgrade","h2c");
//         headers.set_header_key_value("Content-Length","0");
//         headers
//     }
//     /// creating headers with bad request status code is 400
//     pub fn bad_request_headers()->Self{
//         Self::custom(
//             FirstLine{
//                 http_version:HttpVersion::Http1_1,
//                 status:HttpStatus { code: 400 , value: "Bad Request".to_owned() },
//             }
//         )
//     }
//
//
//     /// creating headers with not found response and the status code is 404
//     pub fn not_found_headers()->Self{
//         Self::custom(
//             FirstLine{
//                 http_version:HttpVersion::Http1_1,
//                 status:HttpStatus { code: 404 , value: "Not Found".to_owned() },
//             }
//         )
//     }
//
//     /// for changing the first line of the current header
//     pub fn change_first_line(&mut self,first_line: FirstLine){
//         self.first_line  = first_line;
//     }
//
//     /// making the header have partial content with status code 206
//     /// it`s meaning that the response would be sent is not the full response from the server
//     pub fn change_first_line_to_partial_content(&mut self){
//         self.change_first_line(FirstLine{
//             http_version:HttpVersion::Http1_1,
//             status:HttpStatus { code: 206 , value: "Partial".to_owned() },
//         });
//     }
//
//
//     /// creating headers with partial  content and the status code is 206
//     pub fn success_partial_content()->Self{
//         Self::custom(
//             FirstLine{
//                 http_version:HttpVersion::Http1_1,
//                 status:HttpStatus { code: 206 , value: "Partial".to_owned() },
//             }
//         )
//     }
//
//
//     /// for returning success response headers with 200 status code
//     pub fn success()->Self{
//         Self::custom(
//             FirstLine{
//                 http_version:HttpVersion::Http1_1,
//                 status:HttpStatus { code: 200 , value: "OK".to_owned() },
//             }
//         )
//     }
//
// }
// /// to provide writeable http version to be responded
// pub enum HttpVersion {
//     Http1,
//     Http1_1,
//     Http2,
//     Http3
// }
//
// impl HttpVersion {
//
//     /// converting http version to bytes
//     /// #[&[u8]]
//     pub const fn to_bytes(&self)->&[u8]{
//             self.to_str().as_bytes()
//     }
//
//
//     /// converting http version to string slice
//     /// #[&str]
//     pub const fn to_str(&self)->&str{
//         match self {
//             HttpVersion::Http1 => {"HTTP/1.0"}
//             HttpVersion::Http1_1 => {"HTTP/1.1"}
//             HttpVersion::Http2 => {"HTTP/2"}
//             HttpVersion::Http3 => {"HTTP/3"}
//         }
//     }
// }
// /// for provide status code and status label for `ResponseHeadersBuilder`
// pub struct HttpStatus {
//     pub code:u16,
//     pub value:String
// }
//
//
//
//
// /// wrapper struct for [HttpVersion] and [HttpStatus]
// pub struct FirstLine {
//     pub http_version:HttpVersion,
//     pub status:HttpStatus
// }
// impl FirstLine {
//     pub fn to_bytes(&self)->Vec<u8>{
//         let mut bytes = Vec::with_capacity(1024);
//         let version =
//         match self.http_version {
//             HttpVersion::Http1 => { "HTTP/1.0" }
//             HttpVersion::Http1_1 => { "HTTP/1.1" }
//             HttpVersion::Http2 => { "HTTP/2" }
//             HttpVersion::Http3 => { "HTTP/3" }
//         }.as_bytes();
//         bytes.extend_from_slice(version);
//         bytes.extend_from_slice(format!(" {} {}\r\n",self.status.code,self.status.value).as_bytes());
//         bytes
//     }
// }
// #[doc(hidden)]
// pub struct BodyResponseBuilder<'a> {
//     mechanism:HandlingResponseMechanism<'a>,
// }
// impl <'a> BodyResponseBuilder<'a> {
//     pub fn new(mechanism:HandlingResponseMechanism<'a>)->Self{
//         Self{
//             mechanism
//         }
//     }
// }
//
// #[doc(hidden)]
// pub enum HandlingResponseMechanism<'a> {
//     File(&'a[&'a str]),
//     NormalResponse(&'a[u8]),
//     None
// }
//
// /// for creating custom response
// #[doc(hidden)]
// pub struct ResponseBuilder<'a>{
//
//     pub headers:HeaderResponseBuilder,
//     body:BodyResponseBuilder<'a>
// }
//

// for building custom response for clients within http request
// impl <'a> ResponseBuilder<'a> {
//
//
//     /// return empty body response with
//     pub fn empty()->ResponseBuilder<'a>{
//         Self{
//             headers:HeaderResponseBuilder::success(),
//             body:BodyResponseBuilder::new(HandlingResponseMechanism::NormalResponse(
//                 b""
//             ))
//         }
//     }
//     /// for sending custom bytes as server response
//     pub fn from_bytes_response(bytes:&'a [u8])->ResponseBuilder<'a>{
//         let mut headers = HeaderResponseBuilder::success();
//         headers.set_header_key_value("Content-Length",bytes.len());
//         let  body =
//         BodyResponseBuilder::new(
//             HandlingResponseMechanism::NormalResponse(
//                 bytes
//             )
//         );
//         Self {
//             headers,
//             body
//         }
//     }
//
//
//     /// for sending ['&str'] data type as response
//     pub fn from_str(str:&'a str)->ResponseBuilder<'a>{
//         let  res = Self::from_bytes_response(str.as_bytes());
//         res
//     }
//
//     /// sending ref [String] type to clients as response
//     pub fn from_string_ref(data:&'a String)->ResponseBuilder<'a>{ Self::from_bytes_response(data.as_bytes())}
//
//
//     pub  fn to_bytes(&self)->Option<Vec<u8>>{
//         let this = self;
//         let mut res = this.headers.first_line.to_bytes();
//         res.extend_from_slice(this.headers.data.as_slice());
//         match &self.body.mechanism {
//             HandlingResponseMechanism::NormalResponse(bytes)=>{
//                 res.extend_from_slice(b"\r\n");
//                 res.extend_from_slice(*bytes);
//                 Some(res)
//             }
//             HandlingResponseMechanism::File(_files)=>{
//                 None
//             }
//             _ => {
//                 None
//             }
//         }
//     }
// }
//
//