Struct afire::Header

source ·
pub struct Header {
    pub name: HeaderType,
    pub value: String,
}
Expand description

Http header. Has a name and a value.

Fields§

§name: HeaderType

Name of the Header

§value: String

Value of the Header

Implementations§

source§

impl Header

source

pub fn new(name: impl Into<HeaderType>, value: impl AsRef<str>) -> Header

Make a new header from a name and a value. The name must implement Into<HeaderType>, so it can be a string or a HeaderType. The value can be anything that implements AsRef<str>, including a String, or &str.

Example
let header1 = Header::new("Content-Type", "text/html");
let header2 = Header::new("Access-Control-Allow-Origin", "*");
Examples found in repository?
examples/basic/middleware.rs (line 42)
41
42
43
44
    fn post(&self, _req: &Request, res: &mut Response) -> MiddleResult {
        res.headers.push(Header::new("X-Example", "Middleware"));
        MiddleResult::Continue
    }
More examples
Hide additional examples
examples/basic/serve_static.rs (line 31)
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
    fn exec(&self) {
        // Create a new Server instance on localhost port 8080
        let mut server = Server::<()>::new("localhost", 8080);

        // Make a new static file server with a path
        extension::ServeStatic::new(STATIC_DIR)
            // The middleware priority is by most recently defined.
            // The middleware function takes 3 parameters: the request, the response, and weather the file was loaded successfully.
            // In your middleware you can modify the response and the bool.
            .middleware(|req, res, _suc| {
                // Print path served
                println!("Served: {}", req.path);
                // Return none to not mess with response
                // Or in this case add a header and pass through the success value
                res.headers.push(Header::new("X-Static", "true"));
            })
            // Function that runs when no file is found to serve
            // This will run before middleware
            .not_found(|_req, _dis| {
                Response::new()
                    .status(Status::NotFound)
                    .text("Page Not Found!")
            })
            // Add an extra mime type to the server
            // It has a lot already
            .mime_type("key", "value")
            // Set serve path
            .path(STATIC_PATH)
            // Attach the middleware to the server
            .attach(&mut server);

        // View the file at http://localhost:8080
        // You should also see a favicon in the browser tab

        // Start the server
        // This will block the current thread
        server.start().unwrap();
    }
examples/basic/header.rs (line 32)
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
    fn exec(&self) {
        // Create a new Server instance on localhost port 8080
        let mut server = Server::<()>::new("localhost", 8080)
            // Define server wide default headers
            // These will be send with every response
            // If the same header is defined in the route it will be put before the default header
            // Although it is not guaranteed to be the one picked by the client it usually is
            // At the bottom of this file is a representation of the order of the headers
            .default_header("X-Server-Header", "This is a server wide header")
            // You can also use the HeaderType enum to define a header type
            // This is also true with the .header method on the Response struct
            .default_header(HeaderType::Server, "afire");

        // Define a route to redirect to another website
        server.route(Method::GET, "/", |_req| {
            // Because this is all bout headers I have put the header vector here
            let headers = vec![
                // Tell the client what type of data we are sending
                afire::Header::new(HeaderType::ContentType, "text/html"),
                // Tell the client to redirect to another website
                afire::Header::new(HeaderType::Location, "https://connorcode.com"),
                // Custom header
                afire::Header::new("X-Custom-Header", "This is a custom header"),
            ];

            // Define response body
            // In this case this should only be seen if the client doesn't support redirects for some reason
            let text = "<a href=\"https://connorcode.com\">connorcode</a>";

            // The response code of 308 tells the client to redirect to the location specified in the header
            // There are other response codes you can use too
            // 301 -> Moved Permanently
            // 302 -> Found
            // 303 -> See Other
            // 307 -> Temporary Redirect
            // 308 -> Permanent Redirect
            Response::new()
                .status(Status::PermanentRedirect)
                .text(text)
                .headers(&headers)
        });

        // Now to define a route to handle client headers
        // This will just echo the headers back to the client
        server.route(Method::GET, "/headers", |req| {
            // Get the headers from the request and make a html string
            let body = req
                .headers
                .iter()
                .fold(String::new(), |old, new| old + &format!("{:?}<br />", new));

            // Create a response with the headers
            Response::new().text(body).content(Content::HTML)
        });

        // You can now goto http://localhost:8080 you should see a redirect to https://connorcode.com
        // And you can goto http://localhost:8080/headers to see the headers your client sent to the server

        // Start the server
        // This will block the current thread
        server.start().unwrap();
    }
source

pub fn from_string(header: impl AsRef<str>) -> Result<Header>

Convert a string to a header. String must be in the format name: value, or an error will be returned.

Example
let header1 = Header::new(HeaderType::ContentType, "text/html");
let header2 = Header::from_string("Content-Type: text/html").unwrap();

assert_eq!(header1, header2);
source

pub fn params(&self) -> HeaderParams<'_>

Get the parameters of the header.

Trait Implementations§

source§

impl Clone for Header

source§

fn clone(&self) -> Header

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for Header

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Display for Header

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Convert a header to a string In format: name: value.

Example
let header1 = Header::new(HeaderType::ContentType, "text/html");
assert_eq!(header1.to_string(), "Content-Type: text/html");
source§

impl From<Content<'_>> for Header

source§

fn from(x: Content<'_>) -> Self

Converts to this type from the input type.
source§

impl Hash for Header

source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · source§

fn hash_slice<H>(data: &[Self], state: &mut H)where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
source§

impl PartialEq<Header> for Header

source§

fn eq(&self, other: &Header) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl Eq for Header

source§

impl StructuralEq for Header

source§

impl StructuralPartialEq for Header

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for Twhere T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T> ToString for Twhere T: Display + ?Sized,

source§

default fn to_string(&self) -> String

Converts the given value to a String. Read more
source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.