pub struct ServeStatic {
    pub serve_path: String,
    pub data_dir: String,
    pub disabled_files: Vec<String>,
    pub not_found: fn(_: Rc<Request>, _: bool) -> Response,
    pub middleware: Vec<Box<dyn Fn(Rc<Request>, &mut Response, &mut bool) + Send + Sync>>,
    pub types: Vec<(String, String)>,
}
Expand description

Serve Static Content

Fieldsยง

ยงserve_path: String

Path to serve static content on

Defaults to โ€˜/โ€™ (root)

ยงdata_dir: String

Content Path

ยงdisabled_files: Vec<String>

Disabled file paths (relative from data dir)

ยงnot_found: fn(_: Rc<Request>, _: bool) -> Response

Page not found route

ยงmiddleware: Vec<Box<dyn Fn(Rc<Request>, &mut Response, &mut bool) + Send + Sync>>

Middleware

(Request, Static Response, success [eg If file found])

ยงtypes: Vec<(String, String)>

MIME Types

Implementationsยง

sourceยง

impl ServeStatic

source

pub fn new(data_path: impl AsRef<str>) -> Self

Make a new Static File Server

Example
// Import Library
use afire::{Server, extension::ServeStatic, Middleware};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static file server and attach it to the afire server
ServeStatic::new("data/static").attach(&mut server);

server.start().unwrap();
Examples found in repository?
examples/basic/serve_static.rs (line 22)
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();
    }
source

pub fn disable(self, file_path: impl AsRef<str>) -> Self

Disable serving a file Path is relative to the dir being served

Example
// Import Library
use afire::{Server, extension::ServeStatic, Middleware};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static server
ServeStatic::new("data/static")
    // Disable a file from being served
    .disable("index.scss")
    // Attach it to the afire server
    .attach(&mut server);

server.start().unwrap();
source

pub fn disable_vec(self, file_paths: &[impl AsRef<str>]) -> Self

Disable serving many files at once Path is relative to the dir being served

Example
// Import Library
use afire::{Server, extension::ServeStatic, Middleware};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static server
ServeStatic::new("data/static")
    // Disable a vec of files from being served
    .disable_vec(&["index.scss", "index.css.map"])
    // Attach it to the afire server
    .attach(&mut server);

server.start().unwrap();
source

pub fn not_found(self, f: fn(_: Rc<Request>, _: bool) -> Response) -> Self

Set the not found page.

This will run if no file is found to serve or the file is disabled. The bool in the fn parameters is if the file is blocked.

Example
// Import Library
use afire::{Response, Server, extension::ServeStatic, Middleware, Status};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static server
ServeStatic::new("data/static")
    // Set a new file not found page
    .not_found(|_req, _dis| Response::new().status(Status::NotFound).text("Page Not Found!"))
    // Attach it to the afire server
    .attach(&mut server);

server.start().unwrap();
Examples found in repository?
examples/basic/serve_static.rs (lines 35-39)
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();
    }
source

pub fn mime_type(self, key: impl AsRef<str>, value: impl AsRef<str>) -> Self

Add a MIME type to the Static file Server

This extension comes with a lot of builtin MIME types but if you need to add more thats what this is for

The key is the file extension

The value is the MIME type

Example
// Import Library
use afire::{Server, extension::ServeStatic, Middleware};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static server
ServeStatic::new("data/static")
    // Add a new MIME type
    .mime_type(".3gp", "video/3gpp")
    // Attach it to the afire server
    .attach(&mut server);

server.start().unwrap();
Examples found in repository?
examples/basic/serve_static.rs (line 42)
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();
    }
source

pub fn mime_types( self, new_types: &[(impl AsRef<str>, impl AsRef<str>)] ) -> Self

Add a vector of MIME type to the Static file Server

The key is the file extension

The value is the MIME type

Ex: (โ€œhtmlโ€, โ€œtext/htmlโ€)

Example
// Import Library
use afire::{Server, extension::ServeStatic, Middleware};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static server
ServeStatic::new("data/static")
    // Add a new MIME type
    .mime_types(&[("3gp", "video/3gpp")])
    // Attach it to the afire server
    .attach(&mut server);

server.start().unwrap();
source

pub fn middleware( self, f: impl Fn(Rc<Request>, &mut Response, &mut bool) + Send + Sync + 'static ) -> Self

Add a middleware to the serve static extension. Middleware here works much differently to the normal afire middleware. The middleware priority is still 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.

Examples found in repository?
examples/basic/serve_static.rs (lines 26-32)
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();
    }
source

pub fn path(self, path: impl AsRef<str>) -> Self

Set path to serve static files on

Default is โ€˜/โ€™ (root)

Example
// Import Library
use afire::{Server, extension::ServeStatic, Middleware};

// Create a server for localhost on port 8080
let mut server = Server::<()>::new("localhost", 8080);

// Make a new static server
ServeStatic::new("data/static")
    // Set serve path
    .path("/static")
    // Attach it to the afire server
    .attach(&mut server);

server.start().unwrap();
Examples found in repository?
examples/basic/serve_static.rs (line 44)
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();
    }

Trait Implementationsยง

sourceยง

impl Middleware for ServeStatic

sourceยง

fn post_raw( &self, req: Result<Rc<Request>>, res: &mut Result<Response> ) -> MiddleResult

Middleware to run after routes. Because this is the raw version of Middleware::post, it is passed a Result. The default implementation calls Middleware::post if the Result is Ok.
sourceยง

fn pre_raw(&self, req: &mut Result<Request>) -> MiddleResult

Middleware to run before routes. Because this is the raw version of Middleware::pre, it is passed a Result. The default implementation calls Middleware::pre if the Result is Ok.
sourceยง

fn pre(&self, _req: &mut Request) -> MiddleResult

Middleware to run Before Routes
sourceยง

fn post(&self, _req: &Request, _res: &mut Response) -> MiddleResult

Middleware to run After Routes
sourceยง

fn end_raw(&self, req: &Result<Request>, res: &Result<Response>)

Middleware to run after the response has been handled. Because this is the raw version of Middleware::end, it is passed a Result. The default implementation calls Middleware::end if the Result is Ok.
sourceยง

fn end(&self, _req: &Request, _res: &Response)

Middleware ot run after the response has been handled
sourceยง

fn attach<State>(self, server: &mut Server<State>)where Self: 'static + Send + Sync + Sized, State: 'static + Send + Sync,

Attach Middleware to a Server. If you want to get a reference to the serverโ€™s state in your middleware state, you should override this method.

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, 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.