serv4rs 0.1.7

serv4rs is a powerful, pragmatic, and extremely fast web framework for Rust
Documentation
use crate::R;

// macro_rules! assert_err {
//     ($expression:expr, $($pattern:tt)+) => {
//         match $expression {
//             $($pattern)+ => (),
//             ref e => panic!("expected `{}` but got `{:?}`", stringify!($($pattern)+), e),
//         }
//     }
// }

pub fn cors() -> actix_cors::Cors {
    actix_cors::Cors::default()
        // .allowed_origin("https://www.rust-lang.org")
        // .allowed_origin("*")
        // .allowed_origin_fn(|origin, _req_head| origin.as_bytes().ends_with(b".rust-lang.org"))
        .allowed_methods(vec!["GET", "POST", "DELETE", "PUT", "HEAD"])
        .allowed_headers(vec![
            actix_web::http::header::CONTENT_TYPE,
            actix_web::http::header::AUTHORIZATION,
            actix_web::http::header::ACCEPT,
        ])
        .max_age(3600)
}

#[rustfmt::skip]
pub fn default_headers() -> actix_web::middleware::DefaultHeaders {
    
    let mut default_headers = actix_web::middleware::DefaultHeaders::new().add(("X-Version", "1.0"));
    let mut secure_headers = http::header::HeaderMap::new();

    armor::armor(&mut secure_headers);

    for (key, value) in secure_headers.iter() {
        default_headers = default_headers.add((key.to_string(), format!("{:?}", value)));
    }

    default_headers
    
}

// PathVariable 参数验证
pub fn validate_path_variable() -> actix_web_validator::PathConfig {
    actix_web_validator::PathConfig::default().error_handler(|err, _| {
        let json_error = match &err {
            actix_web_validator::Error::Validate(error) => {
                R::<String>::failed(413, error.to_string())
            }
            _ => R::<String>::failed(413, err.to_string()),
        };
        actix_web::error::InternalError::from_response(
            err,
            actix_web::HttpResponse::Ok().json(json_error),
        )
        .into()
    })
}

// QueryString 参数验证
pub fn validate_query_string() -> actix_web_validator::QsQueryConfig {
    actix_web_validator::QsQueryConfig::default().error_handler(|err, _| {
        let json_error = match &err {
            actix_web_validator::Error::Validate(error) => {
                R::<String>::failed(413, error.to_string())
            }
            _ => R::<String>::failed(413, err.to_string()),
        };
        actix_web::error::InternalError::from_response(
            err,
            actix_web::HttpResponse::Ok().json(json_error),
        )
        .into()
    })
}

// JsonBody 验证
pub fn validate_json_body() -> actix_web_validator::JsonConfig {
    actix_web_validator::JsonConfig::default()
        .limit(2_097_152) // 2mb
        .error_handler(|err, _| {
            let json_error = R::<String>::failed(400, err.to_string());
            actix_web::error::InternalError::from_response(
                err,
                actix_web::HttpResponse::BadRequest().json(json_error),
            )
            .into()
        })
}

// FormData 参数验证
pub fn validate_form_data() -> actix_web_validator::FormConfig {
    actix_web_validator::FormConfig::default()
        .limit(32_768)
        .error_handler(|err, _| {
            let json_error = match &err {
                actix_web_validator::Error::Validate(error) => {
                    R::<String>::failed(414, error.to_string())
                }
                _ => R::<String>::failed(414, err.to_string()),
            };
            actix_web::error::InternalError::from_response(
                err,
                actix_web::HttpResponse::Ok().json(json_error),
            )
            .into()
        })
}

pub fn multipart_form_config(max_size: usize) -> actix_easy_multipart::MultipartFormConfig {
    let the_max_size = max_size;
    actix_easy_multipart::MultipartFormConfig::default()
        .total_limit(max_size)
        .error_handler(move |err, _| {
            let json_error = R::<String>::failed(
                400,
                format!(
                    "{} The upload file max size is {} Bytes",
                    err.to_string(),
                    the_max_size
                ),
            );
            actix_web::error::InternalError::from_response(
                err,
                actix_web::HttpResponse::BadRequest().json(json_error),
            )
            .into()
        })
}

pub fn multipart_temp_folder_config(
    tempfolder: &str,
) -> actix_easy_multipart::tempfile::TempfileConfig {
    actix_easy_multipart::tempfile::TempfileConfig::default().directory(tempfolder)
}

pub fn normalize_path_config() -> actix_web::middleware::NormalizePath {
    actix_web::middleware::NormalizePath::new(actix_web::middleware::TrailingSlash::Trim)
}