loadstar 0.0.7

A simple web framework for rust
Documentation
use ascii::AsciiString;
use maud::Markup;
use tiny_http::{Header, Request, Response};

use crate::template::Template;

/// Returns a 404 response
pub fn respond_not_found(request: Request) {
    let response = Response::from_string("Not Found").with_status_code(404);

    let _ = request.respond(response);
}

/// Renders a template
pub fn respond_template(request: Request, template: impl Template) {
    let response = Response::from_string(template.render())
        .with_header(Header {
            field: "Content-Type".parse().unwrap(),
            value: AsciiString::from_ascii("text/html; charset=utf8").unwrap(),
        });

    let _ = request.respond(response);
}

/// Renders html
pub fn respond_html(request: Request, content: Markup) {
    let response = Response::from_string(content);
    let response = response.with_header(Header {
        field: "Content-Type".parse().unwrap(),
        value: AsciiString::from_ascii("text/html; charset=utf8").unwrap(),
    });

    let _ = request.respond(response);
}

/// Redirects the user to another route
pub fn respond_redirect(request: Request, new_route: &str) {
    let response = Response::from_string("Redirect");
    let response = response.with_header(Header {
        field: "Content-Type".parse().unwrap(),
        value: AsciiString::from_ascii("text/html").unwrap(),
    });
    let response = response.with_header(Header {
        field: "Location".parse().unwrap(),
        value: AsciiString::from_ascii(new_route).unwrap(),
    });
    let response = response.with_status_code(302);

    let _ = request.respond(response);
}

/// Redirects the user to another route while also adding a cookie
pub fn respond_redirect_cookie(request: Request, new_route: &str, cookie_name: &str, cookie_value: &str) {
    let response = Response::from_string("Redirect")
        .with_header(Header {
            field: "Content-Type".parse().unwrap(),
            value: AsciiString::from_ascii("text/html").unwrap(),
        })
        .with_header(Header {
            field: "Location".parse().unwrap(),
            value: AsciiString::from_ascii(new_route).unwrap(),
        })
        .with_header(Header {
            field: "Set-Cookie".parse().unwrap(),
            value: AsciiString::from_ascii(format!("{}={}", cookie_name, cookie_value)).unwrap(),
        })
        .with_status_code(302);


    let _ = request.respond(response);
}