Joining all values by a priority

Our server has four sources of address settings:

  • The configuration file
  • The environment variable
  • The command-line parameter
  • The default value

We have to join these in this order. It's simple to implement this using a set of options and using the or method to set a value if the option doesn't contain anything. Use the following code to get address values from all of the sources:

let addr = matches.value_of("address")
.map(|s| s.to_owned())
.or(env::var("ADDRESS").ok())
.and_then(|addr| addr.parse().ok())
.or(config.map(|config| config.address))
.or_else(|| Some(([127, 0, 0, 1], 8080).into()))
.unwrap();

At first, this code takes a value from the --address command-line parameter. If it doesn't contain any value, the code tries to get a value from the ADDRESS environment variable. After that, we try to parse a textual value to the socket address. If all these steps fail, we can try to get a value from the Config instance that we read from microservice.toml.  We will use the default address value if the value wasn't set by a user. In the previous address-parsing code, we also parsed the default value from a string. In this code, we use a tuple to construct the SocketAddr instance. Since we are guaranteed to get a value, we unwrap the option to extract it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.98.250