rocket/config/config.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
use std::collections::HashMap;
use std::net::ToSocketAddrs;
use std::path::{Path, PathBuf};
use std::convert::AsRef;
use std::fmt;
use super::custom_values::*;
use {num_cpus, base64};
use config::Environment::*;
use config::{Result, ConfigBuilder, Environment, ConfigError, LoggingLevel};
use config::{Table, Value, Array, Datetime};
use http::private::Key;
/// Structure for Rocket application configuration.
///
/// # Usage
///
/// A `Config` structure is typically built using [`Config::build()`] and
/// builder methods on the returned [`ConfigBuilder`] structure:
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// # #[allow(unused_variables)]
/// 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`](::config) module documentation.
#[derive(Clone)]
pub struct Config {
/// The environment that this configuration corresponds to.
pub environment: Environment,
/// The address to serve on.
pub address: String,
/// The port to serve on.
pub port: u16,
/// The number of workers to run concurrently.
pub workers: u16,
/// Keep-alive timeout in seconds or None if disabled.
pub keep_alive: Option<u32>,
/// Number of seconds to wait without _receiving_ data before closing a
/// connection; disabled when `None`.
pub read_timeout: Option<u32>,
/// Number of seconds to wait without _sending_ data before closing a
/// connection; disabled when `None`.
pub write_timeout: Option<u32>,
/// How much information to log.
pub log_level: LoggingLevel,
/// The secret key.
pub(crate) secret_key: SecretKey,
/// TLS configuration.
pub(crate) tls: Option<TlsConfig>,
/// Streaming read size limits.
pub limits: Limits,
/// Extra parameters that aren't part of Rocket's core config.
pub extras: HashMap<String, Value>,
/// The path to the configuration file this config was loaded from, if any.
pub(crate) config_file_path: Option<PathBuf>,
/// The path root-relative files will be rooted from.
pub(crate) root_path: Option<PathBuf>,
}
macro_rules! config_from_raw {
($config:expr, $name:expr, $value:expr,
$($key:ident => ($type:ident, $set:ident, $map:expr),)+ | _ => $rest:expr) => (
match $name {
$(stringify!($key) => {
super::custom_values::$type($config, $name, $value)
.and_then(|parsed| $map($config.$set(parsed)))
})+
_ => $rest
}
)
}
impl Config {
/// Returns a builder for `Config` structure where the default parameters
/// are set to those of `env`.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// # #[allow(unused_variables)]
/// let config = Config::build(Environment::Staging)
/// .address("127.0.0.1")
/// .port(700)
/// .workers(12)
/// .unwrap();
/// ```
pub fn build(env: Environment) -> ConfigBuilder {
ConfigBuilder::new(env)
}
/// Returns a `Config` with the default parameters for the environment
/// `env`. See [`config`](::config) for a list of defaults.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// let mut my_config = Config::new(Environment::Production);
/// my_config.set_port(1001);
/// ```
pub fn new(env: Environment) -> Config {
Config::default(env)
}
/// 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
///
/// ```rust
/// use rocket::config::Config;
///
/// let mut my_config = Config::active().unwrap();
/// my_config.set_port(1001);
/// ```
pub fn active() -> Result<Config> {
Ok(Config::new(Environment::active()?))
}
/// Returns a `Config` with the default parameters of the development
/// environment. See [`config`](::config) for a list of defaults.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// let mut my_config = Config::development();
/// my_config.set_port(1001);
/// ```
pub fn development() -> Config {
Config::new(Environment::Development)
}
/// Returns a `Config` with the default parameters of the staging
/// environment. See [`config`](::config) for a list of defaults.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// let mut my_config = Config::staging();
/// my_config.set_port(1001);
/// ```
pub fn staging() -> Config {
Config::new(Environment::Staging)
}
/// Returns a `Config` with the default parameters of the production
/// environment. See [`config`](::config) for a list of defaults.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// let mut my_config = Config::production();
/// my_config.set_port(1001);
/// ```
pub fn production() -> Config {
Config::new(Environment::Production)
}
/// Returns the default configuration for the environment `env` given that
/// the configuration was stored at `config_file_path`.
///
/// # Error
///
/// Return a `BadFilePath` error if `path` does not have a parent.
///
/// # Panics
///
/// Panics if randomness cannot be retrieved from the OS.
pub(crate) fn default_from<P>(env: Environment, path: P) -> Result<Config>
where P: AsRef<Path>
{
let mut config = Config::default(env);
let config_file_path = path.as_ref().to_path_buf();
if let Some(parent) = config_file_path.parent() {
config.set_root(parent);
} else {
let msg = "Configuration files must be rooted in a directory.";
return Err(ConfigError::BadFilePath(config_file_path.clone(), msg));
}
config.config_file_path = Some(config_file_path);
Ok(config)
}
/// Returns the default configuration for the environment `env`.
///
/// # Panics
///
/// Panics if randomness cannot be retrieved from the OS.
pub(crate) fn default(env: Environment) -> Config {
// Note: This may truncate if num_cpus::get() / 2 > u16::max. That's okay.
let default_workers = (num_cpus::get() * 2) as u16;
// Use a generated secret key by default.
let key = SecretKey::Generated(Key::generate());
match env {
Development => {
Config {
environment: Development,
address: "localhost".to_string(),
port: 8000,
workers: default_workers,
keep_alive: Some(5),
read_timeout: Some(5),
write_timeout: Some(5),
log_level: LoggingLevel::Normal,
secret_key: key,
tls: None,
limits: Limits::default(),
extras: HashMap::new(),
config_file_path: None,
root_path: None,
}
}
Staging => {
Config {
environment: Staging,
address: "0.0.0.0".to_string(),
port: 8000,
workers: default_workers,
keep_alive: Some(5),
read_timeout: Some(5),
write_timeout: Some(5),
log_level: LoggingLevel::Normal,
secret_key: key,
tls: None,
limits: Limits::default(),
extras: HashMap::new(),
config_file_path: None,
root_path: None,
}
}
Production => {
Config {
environment: Production,
address: "0.0.0.0".to_string(),
port: 8000,
workers: default_workers,
keep_alive: Some(5),
read_timeout: Some(5),
write_timeout: Some(5),
log_level: LoggingLevel::Critical,
secret_key: key,
tls: None,
limits: Limits::default(),
extras: HashMap::new(),
config_file_path: None,
root_path: None,
}
}
}
}
/// Constructs a `BadType` error given the entry `name`, the invalid `val`
/// at that entry, and the `expect`ed type name.
#[inline(always)]
pub(crate) fn bad_type(&self,
name: &str,
actual: &'static str,
expect: &'static str) -> ConfigError {
let id = format!("{}.{}", self.environment, name);
ConfigError::BadType(id, expect, actual, self.config_file_path.clone())
}
/// Sets the configuration `val` for the `name` entry. If the `name` is one
/// of "address", "port", "secret_key", "log", or "workers" (the "default"
/// values), the appropriate value in the `self` Config structure is set.
/// Otherwise, the value is stored as an `extra`.
///
/// For each of the default values, the following `Value` variant is
/// expected. If a different variant is supplied, a `BadType` `Err` is
/// returned:
///
/// * **address**: String
/// * **port**: Integer (16-bit unsigned)
/// * **workers**: Integer (16-bit unsigned)
/// * **keep_alive**: Integer
/// * **log**: String
/// * **secret_key**: String (256-bit base64)
/// * **tls**: Table (`certs` (path as String), `key` (path as String))
pub(crate) fn set_raw(&mut self, name: &str, val: &Value) -> Result<()> {
let (id, ok) = (|val| val, |_| Ok(()));
config_from_raw!(self, name, val,
address => (str, set_address, id),
port => (u16, set_port, ok),
workers => (u16, set_workers, ok),
keep_alive => (u32, set_keep_alive, ok),
read_timeout => (u32, set_read_timeout, ok),
write_timeout => (u32, set_write_timeout, ok),
log => (log_level, set_log_level, ok),
secret_key => (str, set_secret_key, id),
tls => (tls_config, set_raw_tls, id),
limits => (limits, set_limits, ok),
| _ => {
self.extras.insert(name.into(), val.clone());
Ok(())
}
)
}
/// Sets the root directory of this configuration to `root`.
///
/// # Example
///
/// ```rust
/// # use std::path::Path;
/// use rocket::config::{Config, Environment};
///
/// let mut config = Config::new(Environment::Staging);
/// config.set_root("/var/my_app");
///
/// # #[cfg(not(windows))]
/// assert_eq!(config.root().unwrap(), Path::new("/var/my_app"));
/// ```
pub fn set_root<P: AsRef<Path>>(&mut self, path: P) {
self.root_path = Some(path.as_ref().into());
}
/// Sets the address of `self` to `address`.
///
/// # Errors
///
/// If `address` is not a valid IP address or hostname, returns a `BadType`
/// error.
///
/// # Example
///
/// ```rust
/// 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());
/// ```
pub fn set_address<A: Into<String>>(&mut self, address: A) -> Result<()> {
let address = address.into();
if (&*address, 0u16).to_socket_addrs().is_err() {
return Err(self.bad_type("address", "string", "a valid hostname or IP"));
}
self.address = address;
Ok(())
}
/// Sets the `port` of `self` to `port`.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// let mut config = Config::new(Environment::Staging);
/// config.set_port(1024);
/// assert_eq!(config.port, 1024);
/// ```
#[inline]
pub fn set_port(&mut self, port: u16) {
self.port = port;
}
/// Sets the number of `workers` in `self` to `workers`.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Environment};
///
/// let mut config = Config::new(Environment::Staging);
/// config.set_workers(64);
/// assert_eq!(config.workers, 64);
/// ```
#[inline]
pub fn set_workers(&mut self, workers: u16) {
self.workers = workers;
}
/// Sets the keep-alive timeout to `timeout` seconds. If `timeout` is `0`,
/// keep-alive is disabled.
///
/// # Example
///
/// ```rust
/// 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);
/// ```
#[inline]
pub fn set_keep_alive(&mut self, timeout: u32) {
if timeout == 0 {
self.keep_alive = None;
} else {
self.keep_alive = Some(timeout);
}
}
/// Sets the read timeout to `timeout` seconds. If `timeout` is `0`, read
/// timeouts are disabled.
///
/// # Example
///
/// ```rust
/// 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);
/// ```
#[inline]
pub fn set_read_timeout(&mut self, timeout: u32) {
if timeout == 0 {
self.read_timeout = None;
} else {
self.read_timeout = Some(timeout);
}
}
/// Sets the write timeout to `timeout` seconds. If `timeout` is `0`, write
/// timeouts are disabled.
///
/// # Example
///
/// ```rust
/// 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);
/// ```
#[inline]
pub fn set_write_timeout(&mut self, timeout: u32) {
if timeout == 0 {
self.write_timeout = None;
} else {
self.write_timeout = Some(timeout);
}
}
/// 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
///
/// ```rust
/// 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());
/// ```
pub fn set_secret_key<K: Into<String>>(&mut self, key: K) -> Result<()> {
let key = key.into();
let error = self.bad_type("secret_key", "string",
"a 256-bit base64 encoded string");
if key.len() != 44 {
return Err(error);
}
let bytes = match base64::decode(&key) {
Ok(bytes) => bytes,
Err(_) => return Err(error)
};
self.secret_key = SecretKey::Provided(Key::from_master(&bytes));
Ok(())
}
/// Sets the logging level for `self` to `log_level`.
///
/// # Example
///
/// ```rust
/// 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);
/// ```
#[inline]
pub fn set_log_level(&mut self, log_level: LoggingLevel) {
self.log_level = log_level;
}
/// Sets the receive limits in `self` to `limits`.
///
/// # Example
///
/// ```rust
/// use rocket::config::{Config, Limits};
///
/// let mut config = Config::development();
/// config.set_limits(Limits::default().limit("json", 4 * (1 << 20)));
/// ```
#[inline]
pub fn set_limits(&mut self, limits: Limits) {
self.limits = limits;
}
/// Sets the TLS configuration in `self`.
///
/// Certificates are read from `certs_path`. The certificate chain must be
/// in X.509 PEM format. The private key is read from `key_path`. The
/// private key must be an RSA key in either PKCS#1 or PKCS#8 PEM format.
///
/// # Errors
///
/// If reading either the certificates or private key fails, an error of
/// variant `Io` is returned. If either the certificates or private key
/// files are malformed or cannot be parsed, an error of `BadType` is
/// returned.
///
/// # Example
///
/// ```rust
/// use rocket::config::Config;
///
/// # use rocket::config::ConfigError;
/// # fn config_test() -> Result<(), ConfigError> {
/// let mut config = Config::development();
/// config.set_tls("/etc/ssl/my_certs.pem", "/etc/ssl/priv.key")?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "tls")]
pub fn set_tls(&mut self, certs_path: &str, key_path: &str) -> Result<()> {
use http::tls::util::{self, Error};
let pem_err = "malformed PEM file";
// Load the certificates.
let certs = util::load_certs(self.root_relative(certs_path))
.map_err(|e| match e {
Error::Io(e) => ConfigError::Io(e, "tls.certs"),
_ => self.bad_type("tls", pem_err, "a valid certificates file")
})?;
// And now the private key.
let key = util::load_private_key(self.root_relative(key_path))
.map_err(|e| match e {
Error::Io(e) => ConfigError::Io(e, "tls.key"),
_ => self.bad_type("tls", pem_err, "a valid private key file")
})?;
self.tls = Some(TlsConfig { certs, key });
Ok(())
}
#[doc(hidden)]
#[cfg(not(feature = "tls"))]
pub fn set_tls(&mut self, _: &str, _: &str) -> Result<()> {
self.tls = Some(TlsConfig);
Ok(())
}
#[inline(always)]
fn set_raw_tls(&mut self, _paths: (&str, &str)) -> Result<()> {
#[cfg(not(test))]
{ self.set_tls(_paths.0, _paths.1) }
// During unit testing, we don't want to actually read certs/keys.
#[cfg(test)]
{ Ok(()) }
}
/// Sets the extras for `self` to be the key/value pairs in `extras`.
/// encoded string.
///
/// # Example
///
/// ```rust
/// 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);
/// ```
#[inline]
pub fn set_extras(&mut self, extras: HashMap<String, Value>) {
self.extras = extras;
}
/// Returns an iterator over the names and values of all of the extras in
/// `self`.
///
/// # Example
///
/// ```rust
/// 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);
/// ```
#[inline]
pub fn extras<'a>(&'a self) -> impl Iterator<Item=(&'a str, &'a Value)> {
self.extras.iter().map(|(k, v)| (k.as_str(), v))
}
/// Returns `true` if TLS is enabled.
///
/// Always returns `false` if the `tls` compilation feature is not enabled.
pub fn tls_enabled(&self) -> bool {
if cfg!(feature = "tls") {
self.tls.is_some()
} else {
false
}
}
/// Retrieves the secret key from `self`.
#[inline]
pub(crate) fn secret_key(&self) -> &Key {
self.secret_key.inner()
}
/// 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
///
/// ```rust
/// 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());
/// ```
pub fn get_extra<'a>(&'a self, name: &str) -> Result<&'a Value> {
self.extras.get(name).ok_or_else(|| ConfigError::Missing(name.into()))
}
/// 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
///
/// ```rust
/// 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"));
/// ```
pub fn get_str<'a>(&'a self, name: &str) -> Result<&'a str> {
let val = self.get_extra(name)?;
val.as_str().ok_or_else(|| self.bad_type(name, val.type_str(), "a 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
///
/// ```rust
/// 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()));
/// ```
pub fn get_string(&self, name: &str) -> Result<String> {
self.get_str(name).map(|s| s.to_string())
}
/// 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
///
/// ```rust
/// 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));
/// ```
pub fn get_int(&self, name: &str) -> Result<i64> {
let val = self.get_extra(name)?;
val.as_integer().ok_or_else(|| self.bad_type(name, val.type_str(), "an integer"))
}
/// 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
///
/// ```rust
/// 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));
/// ```
pub fn get_bool(&self, name: &str) -> Result<bool> {
let val = self.get_extra(name)?;
val.as_bool().ok_or_else(|| self.bad_type(name, val.type_str(), "a boolean"))
}
/// 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
///
/// ```rust
/// 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));
/// ```
pub fn get_float(&self, name: &str) -> Result<f64> {
let val = self.get_extra(name)?;
val.as_float().ok_or_else(|| self.bad_type(name, val.type_str(), "a float"))
}
/// 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
///
/// ```rust
/// 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());
/// ```
pub fn get_slice(&self, name: &str) -> Result<&Array> {
let val = self.get_extra(name)?;
val.as_array().ok_or_else(|| self.bad_type(name, val.type_str(), "an array"))
}
/// 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
///
/// ```rust
/// 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());
/// ```
pub fn get_table(&self, name: &str) -> Result<&Table> {
let val = self.get_extra(name)?;
val.as_table().ok_or_else(|| self.bad_type(name, val.type_str(), "a table"))
}
/// 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
///
/// ```rust
/// 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));
/// ```
pub fn get_datetime(&self, name: &str) -> Result<&Datetime> {
let val = self.get_extra(name)?;
val.as_datetime()
.ok_or_else(|| self.bad_type(name, val.type_str(), "a datetime"))
}
/// 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
///
/// ```rust
/// 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);
/// ```
pub fn root(&self) -> Option<&Path> {
self.root_path.as_ref().map(|p| p.as_ref())
}
/// 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
///
/// ```rust
/// 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"));
/// # #[cfg(not(windows))]
/// assert_eq!(config.root_relative("/abc"), Path::new("/abc"));
/// # #[cfg(windows)]
/// # assert_eq!(config.root_relative("C:\\abc"), Path::new("C:\\abc"));
/// ```
pub fn root_relative<P: AsRef<Path>>(&self, path: P) -> PathBuf {
let path = path.as_ref();
if path.is_absolute() {
path.into()
} else if let Some(root) = self.root() {
root.join(path)
} else if let Ok(cwd) = ::std::env::current_dir() {
cwd.join(path)
} else {
path.into()
}
}
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut s = f.debug_struct("Config");
s.field("environment", &self.environment);
s.field("address", &self.address);
s.field("port", &self.port);
s.field("workers", &self.workers);
s.field("keep_alive", &self.keep_alive);
s.field("log_level", &self.log_level);
for (key, value) in self.extras() {
s.field(key, &value);
}
s.finish()
}
}
/// Doesn't consider the secret key or config path.
impl PartialEq for Config {
fn eq(&self, other: &Config) -> bool {
self.address == other.address
&& self.port == other.port
&& self.workers == other.workers
&& self.log_level == other.log_level
&& self.keep_alive == other.keep_alive
&& self.environment == other.environment
&& self.extras == other.extras
}
}