Standard library

There are enough functions in the std::env standard module to work with environment variables. It contains the var function to read external values. This function returns a Result with a String value of the variable if it exists, or a VarError error if it doesn't exist. Add the import of the env module to your main.rs file:

use std::env;

We need to replace the following line:

let addr = ([127, 0, 0, 1], 8080).into();

Replace it with the following:

let addr = env::var("ADDRESS")
.unwrap_or_else(|_| "127.0.0.1:8080".into())
.parse()
.expect("can't parse ADDRESS variable");

This new code reads the ADDRESS value. If this value doesn't exist, we won't let the code throw a panic. Instead, we will replace it with the default value, "127.0.0.1:8080", using the unwrap_or_else method call. As the var function returns a String, we also have to convert &'static str into a String instance with the into method call.

If we can't parse an address, we will throw a panic in the except method call.

Your server will now use the addr variable, which takes a value from the ADDRESS environment variable or from the default value.

Environment variables are a simple way of configuring your application. They are also widely supported with hosting or cloud platforms and Docker containers.

Remember that all sensitive data is visible to the system administrator of the host. In Linux, the system administrator can read this data simply by using the cat /proc/`pidof random-service-with-env`/environ` | tr '' ' ' command. This means that it's not a good idea to set the secret key of your bitcoin wallet to the environment variable.
..................Content has been hidden....................

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