Reading the configuration file

Our server will expect to find a configuration file in the current working folder with the name microservice.toml. To read a configuration and convert it to the Config struct, we need to find and read this file if it exists. Add the following code to the main function of the server:

let config = File::open("microservice.toml")
.and_then(|mut file| {
let mut buffer = String::new();
file.read_to_string(&mut buffer)?;
Ok(buffer)
})
.and_then(|buffer| {
toml::from_str::<Config>(&buffer)
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))
})
.map_err(|err| {
warn!("Can't read config file: {}", err);
})
.ok();

The preceding code is a chain of method calls that start with the File instance. We use the open method to open the file and provide the name microservice.toml. The call returns a Result, which we will process in the chain. At the end of the processing, we will convert it to an option using the ok method and ignore any errors that occur during the parsing of the config file. This is because our service also supports environment variables and command-line parameters and has defaults for unset parameters.

When the file is ready, we will try to convert it into a String. We created an empty string, called a buffer, and used the read_to_string method of the File instance to move all of the data into the buffer. This is a synchronous operation. It's suitable for reading a configuration but you shouldn't use it for reading files to send to the client, because it will lock the runtime of the server until the file is read.

After we have read the buffer variable, we will try to parse it as a TOML file into the Config struct. The toml crate has a from_str method in the root namespace of the crate. It expects a type parameter to deserialize and an input string. We use the Config struct for the output type and our buffer for the input. But there is a problem: the File uses io::Error for errors, but from_str uses toml::de:Error for the error type. We can convert the second type to io::Error to make it compatible with the chain of calls.

The penultimate part of the chain is the map_err method call. We use this to write any errors with the configuration file to logs. As you can see, we used the Warn level. Issues with the configuration file are not critical, but it is important to be aware of them because they can affect the configuration. This makes the microservices.toml file optional.

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

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