Skip to main content

ProjectConfig

Struct ProjectConfig 

Source
#[non_exhaustive]
pub struct ProjectConfig { pub debug: bool, pub register_panic_hook: bool, pub secret_key: SecretKey, pub fallback_secret_keys: Vec<SecretKey>, pub auth_backend: AuthBackendConfig, pub database: DatabaseConfig, pub cache: CacheConfig, pub static_files: StaticFilesConfig, pub middlewares: MiddlewareConfig, pub client_ip: ClientIpConfig, pub email: EmailConfig, pub extra: Table, }
Expand description

The configuration for a project.

This is all the project-specific configuration data that can (and makes sense to) be expressed in a TOML configuration file.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§debug: bool

Debug mode flag.

This enables some expensive operations that are useful for debugging, such as logging additional information, and collecting some extra diagnostics for generating error pages. The debug flag also controls whether Cot displays nice error pages. All of this hurts the performance, so it should be disabled for production.

ProjectConfig::default() returns true here when the application is compiled in debug mode, and false when it is compiled in release mode.

§Examples

use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};

let config = ProjectConfig::from_toml(
    r#"
debug = true
"#,
)?;

assert_eq!(config.debug, true);
§register_panic_hook: bool

Whether to register a panic hook.

The panic hook is used to display information about panics in the Cot error pages that are displayed in debug mode.

§Examples

use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};

let config = ProjectConfig::from_toml(
    r#"
register_panic_hook = false
"#,
)?;

assert_eq!(config.register_panic_hook, false);
§secret_key: SecretKey

The secret key used for signing cookies and other sensitive data.

This is a cryptographic key, should be kept secret, and should be set to a random and unique value for each project.

When you want to rotate the secret key, you can move the current key to the fallback_secret_keys list, and set a new key here. Eventually, you can remove the old key from the list.

§Examples

use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};

let config = ProjectConfig::from_toml(
    r#"
secret_key = "123abc"
"#,
)?;

assert_eq!(config.secret_key, SecretKey::from("123abc"));
§fallback_secret_keys: Vec<SecretKey>

Fallback secret keys that can be used to verify old sessions.

This is useful for key rotation, where you can add a new key, gradually migrate sessions to the new key, and then remove the old key.

§Examples

use cot::config::{AuthBackendConfig, ProjectConfig, SecretKey};

let config = ProjectConfig::from_toml(
    r#"
fallback_secret_keys = ["123abc"]
"#,
)?;

assert_eq!(config.fallback_secret_keys, vec![SecretKey::from("123abc")]);
§auth_backend: AuthBackendConfig

The authentication backend to use.

§Examples

use cot::config::{AuthBackendConfig, ProjectConfig};

let config = ProjectConfig::from_toml(
    r#"
[auth_backend]
type = "none"
"#,
)?;

assert_eq!(config.auth_backend, AuthBackendConfig::None);
§database: DatabaseConfig
Available on crate feature db only.

Database configuration.

§Examples

use cot::config::{AuthBackendConfig, DatabaseUrl, ProjectConfig};

let config = ProjectConfig::from_toml(
    r#"
[database]
url = "sqlite::memory:"
"#,
)?;

assert_eq!(
    config.database.url,
    Some(DatabaseUrl::from("sqlite::memory:"))
);
§cache: CacheConfig
Available on crate feature cache only.

Cache subsystem configuration.

§Examples

use std::time::Duration;

use cot::config::{CacheConfig, CacheStoreTypeConfig, ProjectConfig, Timeout};

let config = ProjectConfig::from_toml(
    r#"
[cache]
prefix = "myapp"
max_retries = 3
timeout = "1h"

[cache.store]
type = "memory"
"#,
)?;

assert_eq!(config.cache.prefix, Some("myapp".to_string()));
assert_eq!(config.cache.max_retries, 3);
assert_eq!(
    config.cache.timeout,
    Timeout::After(Duration::from_secs(3600))
);
assert_eq!(config.cache.store.store_type, CacheStoreTypeConfig::Memory);
Ok::<(), cot::Error>(())
§static_files: StaticFilesConfig

Static files configuration.

§Examples

use std::time::Duration;

use cot::config::{AuthBackendConfig, DatabaseUrl, ProjectConfig, StaticFilesPathRewriteMode};

let config = ProjectConfig::from_toml(
    r#"
[static_files]
url = "/assets/"
rewrite = "query_param"
cache_timeout = "1h"
"#,
)?;

assert_eq!(config.static_files.url, "/assets/");
assert_eq!(
    config.static_files.rewrite,
    StaticFilesPathRewriteMode::QueryParam,
);
assert_eq!(
    config.static_files.cache_timeout,
    Some(Duration::from_secs(3600)),
);
§middlewares: MiddlewareConfig

Middleware configuration.

§Examples

use cot::config::{MiddlewareConfig, ProjectConfig};

let config = ProjectConfig::from_toml(
    r#"
[middlewares]
live_reload.enabled = true
"#,
)?;

assert_eq!(config.middlewares.live_reload.enabled, true);
§client_ip: ClientIpConfig

Client IP address detection configuration.

§Examples

use cot::config::ProjectConfig;

let config = ProjectConfig::from_toml(
    r#"
[client_ip]
proxies = ["127.0.0.1/32"]
"#,
)?;

assert_eq!(
    config.client_ip.proxies,
    vec!["127.0.0.1/32".parse().unwrap()]
);
§email: EmailConfig
Available on crate feature email only.

Email backend configuration.

§Examples

use cot::config::{EmailConfig, ProjectConfig};

let config = ProjectConfig::from_toml(
    r#"
[email.transport]
type = "console"
"#,
)?;

assert_eq!(config.email, EmailConfig::default());
§extra: Table

All the config that was not recognized.

This is useful for parsing project-specific config that is not part of any of the predefined fields in ProjectConfig.

§Examples

use cot::config::ProjectConfig;
use serde::Deserialize;

let config = ProjectConfig::from_toml(
    r#"
[my_cot_project]
foo = "bar"
"#,
)?;

#[derive(Deserialize)]
struct MyCotProjectConfig {
    foo: String,
}

let my_config: MyCotProjectConfig = config
    .extra
    .get("my_cot_project")
    .ok_or("could not find the project config")?
    .clone()
    .try_into()?;
assert_eq!(my_config.foo, "bar");

Implementations§

Source§

impl ProjectConfig

Source

pub fn builder() -> ProjectConfigBuilder

Create a new ProjectConfigBuilder to build a ProjectConfig.

§Examples
use cot::config::ProjectConfig;

let config = ProjectConfig::builder().build();
Source

pub fn dev_default() -> ProjectConfig

Create a new ProjectConfig with the default values for development.

This is useful for development purposes, where you want to have a configuration that you can just run as quickly as possible. This is mainly useful for tests and other local development activities.

Note that what this function returns exactly is not guaranteed to be the same across different versions of Cot. It’s meant to be used as a starting point for your development configuration and is subject to change.

§Examples
use cot::config::ProjectConfig;

let config = ProjectConfig::dev_default();
Source

pub fn from_toml(toml_content: &str) -> Result<ProjectConfig>

Create a new ProjectConfig from a TOML string.

§Errors

This function will return an error if the TOML fails to parse as a ProjectConfig.

§Examples
use cot::config::ProjectConfig;

let toml = r#"
   secret_key = "123abc"
"#;
let config = ProjectConfig::from_toml(toml)?;

Trait Implementations§

Source§

impl Clone for ProjectConfig

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

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

Performs copy-assignment from source. Read more
Source§

impl Debug for ProjectConfig

Source§

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

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

impl Default for ProjectConfig

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for ProjectConfig

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl JsonSchema for ProjectConfig

Available on crate feature _internal_config-docs only.
Source§

fn schema_name() -> Cow<'static, str>

The name of the generated JSON Schema. Read more
Source§

fn schema_id() -> Cow<'static, str>

Returns a string that uniquely identifies the schema produced by this type. Read more
Source§

fn json_schema(generator: &mut SchemaGenerator) -> Schema

Generates a JSON Schema for this type. Read more
Source§

fn inline_schema() -> bool

Whether JSON Schemas generated for this type should be included directly in parent schemas, rather than being re-used where possible using the $ref keyword. Read more
Source§

impl Serialize for ProjectConfig

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> Fake for T

Source§

fn fake<U>(&self) -> U
where Self: FakeBase<U>,

Source§

fn fake_with_rng<U, R>(&self, rng: &mut R) -> U
where R: RngExt + ?Sized, Self: FakeBase<U>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FromRef<T> for T
where T: Clone,

Source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where 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> IntoApi for T

Source§

fn into_api<A>(self) -> UseApi<T, A>
where T: Sized,

into UseApi
Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoField<Auto<T>> for T

Source§

fn into_field(self) -> Auto<T>

Available on crate feature db only.
Converts the type to the field type.
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

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, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

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

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more