Struct rocket::config::Config

source ·
pub struct Config {
    pub environment: Environment,
    pub address: String,
    pub port: u16,
    pub workers: u16,
    pub keep_alive: Option<u32>,
    pub read_timeout: Option<u32>,
    pub write_timeout: Option<u32>,
    pub log_level: LoggingLevel,
    pub limits: Limits,
    pub extras: HashMap<String, Value>,
    /* private fields */
}
Expand description

Structure for Rocket application configuration.

§Usage

A Config structure is typically built using Config::build() and builder methods on the returned ConfigBuilder structure:

use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .address("127.0.0.1")
    .port(700)
    .workers(12)
    .unwrap();

§General Configuration

For more information about Rocket’s configuration, see the config module documentation.

Fields§

§environment: Environment

The environment that this configuration corresponds to.

§address: String

The address to serve on.

§port: u16

The port to serve on.

§workers: u16

The number of workers to run concurrently.

§keep_alive: Option<u32>

Keep-alive timeout in seconds or None if disabled.

§read_timeout: Option<u32>

Number of seconds to wait without receiving data before closing a connection; disabled when None.

§write_timeout: Option<u32>

Number of seconds to wait without sending data before closing a connection; disabled when None.

§log_level: LoggingLevel

How much information to log.

§limits: Limits

Streaming read size limits.

§extras: HashMap<String, Value>

Extra parameters that aren’t part of Rocket’s core config.

Implementations§

source§

impl Config

source

pub fn build(env: Environment) -> ConfigBuilder

Returns a builder for Config structure where the default parameters are set to those of env.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .address("127.0.0.1")
    .port(700)
    .workers(12)
    .unwrap();
source

pub fn new(env: Environment) -> Config

Returns a Config with the default parameters for the environment env. See config for a list of defaults.

§Example
use rocket::config::{Config, Environment};

let mut my_config = Config::new(Environment::Production);
my_config.set_port(1001);
source

pub fn active() -> Result<Config>

Returns a Config with the default parameters of the active environment as determined by the ROCKET_ENV environment variable.

If ROCKET_ENV is not set, the returned Config uses development environment parameters when the application was compiled in debug mode and production environment parameters when the application was compiled in release mode.

This is equivalent to Config::new(Environment::active()?).

§Errors

Returns a BadEnv error if ROCKET_ENV is set and contains an invalid or unknown environment name.

§Example
use rocket::config::Config;

let mut my_config = Config::active().unwrap();
my_config.set_port(1001);
source

pub fn development() -> Config

Returns a Config with the default parameters of the development environment. See config for a list of defaults.

§Example
use rocket::config::{Config, Environment};

let mut my_config = Config::development();
my_config.set_port(1001);
source

pub fn staging() -> Config

Returns a Config with the default parameters of the staging environment. See config for a list of defaults.

§Example
use rocket::config::{Config, Environment};

let mut my_config = Config::staging();
my_config.set_port(1001);
source

pub fn production() -> Config

Returns a Config with the default parameters of the production environment. See config for a list of defaults.

§Example
use rocket::config::{Config, Environment};

let mut my_config = Config::production();
my_config.set_port(1001);
source

pub fn set_root<P: AsRef<Path>>(&mut self, path: P)

Sets the root directory of this configuration to root.

§Example
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
config.set_root("/var/my_app");

assert_eq!(config.root().unwrap(), Path::new("/var/my_app"));
source

pub fn set_address<A: Into<String>>(&mut self, address: A) -> Result<()>

Sets the address of self to address.

§Errors

If address is not a valid IP address or hostname, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
assert!(config.set_address("localhost").is_ok());
assert!(config.set_address("::").is_ok());
assert!(config.set_address("?").is_err());
source

pub fn set_port(&mut self, port: u16)

Sets the port of self to port.

§Example
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
config.set_port(1024);
assert_eq!(config.port, 1024);
source

pub fn set_workers(&mut self, workers: u16)

Sets the number of workers in self to workers.

§Example
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
config.set_workers(64);
assert_eq!(config.workers, 64);
source

pub fn set_keep_alive(&mut self, timeout: u32)

Sets the keep-alive timeout to timeout seconds. If timeout is 0, keep-alive is disabled.

§Example
use rocket::config::Config;

let mut config = Config::development();

// Set keep-alive timeout to 10 seconds.
config.set_keep_alive(10);
assert_eq!(config.keep_alive, Some(10));

// Disable keep-alive.
config.set_keep_alive(0);
assert_eq!(config.keep_alive, None);
source

pub fn set_read_timeout(&mut self, timeout: u32)

Sets the read timeout to timeout seconds. If timeout is 0, read timeouts are disabled.

§Example
use rocket::config::Config;

let mut config = Config::development();

// Set read timeout to 10 seconds.
config.set_read_timeout(10);
assert_eq!(config.read_timeout, Some(10));

// Disable read timeouts.
config.set_read_timeout(0);
assert_eq!(config.read_timeout, None);
source

pub fn set_write_timeout(&mut self, timeout: u32)

Sets the write timeout to timeout seconds. If timeout is 0, write timeouts are disabled.

§Example
use rocket::config::Config;

let mut config = Config::development();

// Set write timeout to 10 seconds.
config.set_write_timeout(10);
assert_eq!(config.write_timeout, Some(10));

// Disable write timeouts.
config.set_write_timeout(0);
assert_eq!(config.write_timeout, None);
source

pub fn set_secret_key<K: Into<String>>(&mut self, key: K) -> Result<()>

Sets the secret_key in self to key which must be a 256-bit base64 encoded string.

§Errors

If key is not a valid 256-bit base64 encoded string, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
let key = "8Xui8SN4mI+7egV/9dlfYYLGQJeEx4+DwmSQLwDVXJg=";
assert!(config.set_secret_key(key).is_ok());
assert!(config.set_secret_key("hello? anyone there?").is_err());
source

pub fn set_log_level(&mut self, log_level: LoggingLevel)

Sets the logging level for self to log_level.

§Example
use rocket::config::{Config, LoggingLevel, Environment};

let mut config = Config::new(Environment::Staging);
config.set_log_level(LoggingLevel::Critical);
assert_eq!(config.log_level, LoggingLevel::Critical);
source

pub fn set_limits(&mut self, limits: Limits)

Sets the receive limits in self to limits.

§Example
use rocket::config::{Config, Limits};

let mut config = Config::development();
config.set_limits(Limits::default().limit("json", 4 * (1 << 20)));
source

pub fn set_extras(&mut self, extras: HashMap<String, Value>)

Sets the extras for self to be the key/value pairs in extras. encoded string.

§Example
use std::collections::HashMap;
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);

// Create the `extras` map.
let mut extras = HashMap::new();
extras.insert("another_port".to_string(), 1044.into());
extras.insert("templates".to_string(), "my_dir".into());

config.set_extras(extras);
source

pub fn extras<'a>(&'a self) -> impl Iterator<Item = (&'a str, &'a Value)>

Returns an iterator over the names and values of all of the extras in self.

§Example
use std::collections::HashMap;
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
assert_eq!(config.extras().count(), 0);

// Add a couple of extras to the config.
let mut extras = HashMap::new();
extras.insert("another_port".to_string(), 1044.into());
extras.insert("templates".to_string(), "my_dir".into());
config.set_extras(extras);

assert_eq!(config.extras().count(), 2);
source

pub fn tls_enabled(&self) -> bool

Returns true if TLS is enabled.

Always returns false if the tls compilation feature is not enabled.

source

pub fn get_extra<'a>(&'a self, name: &str) -> Result<&'a Value>

Attempts to retrieve the extra named name as a raw value.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing.

§Example
use rocket::config::{Config, Environment, Value};

let config = Config::build(Environment::Staging)
    .extra("name", "value")
    .unwrap();

assert_eq!(config.get_extra("name"), Ok(&Value::String("value".into())));
assert!(config.get_extra("other").is_err());
source

pub fn get_str<'a>(&'a self, name: &str) -> Result<&'a str>

Attempts to retrieve the extra named name as a borrowed string.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not a string, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .extra("my_extra", "extra_value")
    .unwrap();

assert_eq!(config.get_str("my_extra"), Ok("extra_value"));
source

pub fn get_string(&self, name: &str) -> Result<String>

Attempts to retrieve the extra named name as an owned string.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not a string, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .extra("my_extra", "extra_value")
    .unwrap();

assert_eq!(config.get_string("my_extra"), Ok("extra_value".to_string()));
source

pub fn get_int(&self, name: &str) -> Result<i64>

Attempts to retrieve the extra named name as an integer.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not an integer, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .extra("my_extra", 1025)
    .unwrap();

assert_eq!(config.get_int("my_extra"), Ok(1025));
source

pub fn get_bool(&self, name: &str) -> Result<bool>

Attempts to retrieve the extra named name as a boolean.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not a boolean, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .extra("my_extra", true)
    .unwrap();

assert_eq!(config.get_bool("my_extra"), Ok(true));
source

pub fn get_float(&self, name: &str) -> Result<f64>

Attempts to retrieve the extra named name as a float.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not a float, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .extra("pi", 3.14159)
    .unwrap();

assert_eq!(config.get_float("pi"), Ok(3.14159));
source

pub fn get_slice(&self, name: &str) -> Result<&Array>

Attempts to retrieve the extra named name as a slice of an array.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not an array, returns a BadType error.

§Example
use rocket::config::{Config, Environment};

let config = Config::build(Environment::Staging)
    .extra("numbers", vec![1, 2, 3])
    .unwrap();

assert!(config.get_slice("numbers").is_ok());
source

pub fn get_table(&self, name: &str) -> Result<&Table>

Attempts to retrieve the extra named name as a table.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not a table, returns a BadType error.

§Example
use std::collections::BTreeMap;
use rocket::config::{Config, Environment};

let mut table = BTreeMap::new();
table.insert("my_value".to_string(), 1);

let config = Config::build(Environment::Staging)
    .extra("my_table", table)
    .unwrap();

assert!(config.get_table("my_table").is_ok());
source

pub fn get_datetime(&self, name: &str) -> Result<&Datetime>

Attempts to retrieve the extra named name as a datetime value.

§Errors

If an extra with name doesn’t exist, returns an Err of Missing. If an extra with name does exist but is not a datetime, returns a BadType error.

§Example
use rocket::config::{Config, Environment, Value, Datetime};

let date = "1979-05-27T00:32:00-07:00".parse::<Datetime>().unwrap();

let config = Config::build(Environment::Staging)
    .extra("my_date", Value::Datetime(date.clone()))
    .unwrap();

assert_eq!(config.get_datetime("my_date"), Ok(&date));
source

pub fn root(&self) -> Option<&Path>

Returns the root path of the configuration, if one is known.

For configurations loaded from a Rocket.toml file, this will be the directory in which the file is stored. For instance, if the configuration file is at /tmp/Rocket.toml, the path /tmp is returned. For other configurations, this will be the path set via Config::set_root() or ConfigBuilder::root().

§Example
use std::env::current_dir;
use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);
assert_eq!(config.root(), None);

let cwd = current_dir().expect("have cwd");
config.set_root(&cwd);
assert_eq!(config.root().unwrap(), cwd);
source

pub fn root_relative<P: AsRef<Path>>(&self, path: P) -> PathBuf

Returns path relative to this configuration.

The path that is returned depends on whether:

  1. Whether path is absolute or relative.
  2. Whether there is a Config::root() configured.
  3. Whether there is a current directory.

If path is absolute, it is returned unaltered. Otherwise, if path is relative and there is a root configured, the root is prepended to path and the newlt concatenated path is returned. Otherwise, if there is a current directory, it is preprended to path and the newly concatenated path is returned. Finally, if all else fails, the path is simply returned.

§Example
use std::path::Path;
use std::env::current_dir;

use rocket::config::{Config, Environment};

let mut config = Config::new(Environment::Staging);

let cwd = current_dir().expect("have cwd");
config.set_root(&cwd);
assert_eq!(config.root().unwrap(), cwd);

assert_eq!(config.root_relative("abc"), cwd.join("abc"));
assert_eq!(config.root_relative("/abc"), Path::new("/abc"));

Trait Implementations§

source§

impl Clone for Config

source§

fn clone(&self) -> Config

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 Config

source§

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

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

impl PartialEq for Config

Doesn’t consider the secret key or config path.

source§

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

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

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

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Auto Trait Implementations§

§

impl Freeze for Config

§

impl RefUnwindSafe for Config

§

impl Send for Config

§

impl Sync for Config

§

impl Unpin for Config

§

impl UnwindSafe for Config

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, I> AsResult<T, I> for T
where I: Input,

source§

fn as_result(self) -> Result<T, ParseErr<I>>

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<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dst. 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 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.

§

impl<T> IntoCollection<T> for T

§

fn into_collection<A>(self) -> SmallVec<A>
where A: Array<Item = T>,

Converts self into a collection.
§

fn mapped<U, F, A>(self, f: F) -> SmallVec<A>
where F: FnMut(T) -> U, A: Array<Item = U>,

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 = 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 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<T> Typeable for T
where T: Any,

source§

fn get_type(&self) -> TypeId

Get the TypeId of this object.
source§

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

source§

fn vzip(self) -> V