1use std::fmt::Display;
2use std::io;
3use std::io::BufWriter;
4use std::io::Write;
5use std::net::TcpStream;
6
7use crate::Body;
8
9#[derive(Debug)]
10pub struct Header {
11 writer: BufWriter<TcpStream>,
12 content: String
13}
14
15impl Header {
16 pub fn new(writer: BufWriter<TcpStream>, content: String) -> Header {
17 Header { writer, content }
18 }
19
20 pub fn set_header<K: Display, V: Display>(mut self, key: K, value: V) -> Header {
21 let content = format!("{}: {}\r\n", key, value);
22
23 self.content += &content;
24 self
25 }
26
27 pub fn flush(mut self) -> io::Result<Body> {
28 let bytes = self.content.as_bytes();
29
30 self.writer.write_all(bytes)?;
31 self.writer.write_all(b"\r\n")?;
32 self.writer.flush()?;
33
34 self.content.clear();
35
36 let body = Body::new(self.writer, self.content);
37
38 Ok(body)
39 }
40
41 pub fn text<T: Display>(self, text: T) -> io::Result<()> {
42 self.set_header("Content-Type", "text/plain").flush()?
43 .add_to_body(text).flush()?;
44
45 Ok(())
46 }
47
48 pub fn html<H: Display>(self, html: H) -> io::Result<()> {
49 self.set_header("Content-Type", "text/html").flush()?
50 .add_to_body(html).flush()?;
51
52 Ok(())
53 }
54
55 pub fn json<J: Display>(self, json: J) -> io::Result<()> {
56 self.set_header("Content-Type", "application/json").flush()?
57 .add_to_body(json).flush()?;
58
59 Ok(())
60 }
61}