Building a parser

The process of building a parser is quite simple. You will create an App instance and feed this type with the Arg instances. The App also has methods that can be used to set information about the application. Add the following code to the main function of our server:

let matches = App::new(crate_name!())
.version(crate_version!())
.author(crate_authors!())
.about(crate_description!())
.arg(Arg::with_name("address")
.short("a")
.long("address")
.value_name("ADDRESS")
.help("Sets an address")
.takes_value(true))
.arg(Arg::with_name("config")
.short("c")
.long("config")
.value_name("FILE")
.help("Sets a custom config file")
.takes_value(true))
.get_matches();

First, we create an App instance with a new method that expects the name of the crate. We provide this using the crate_name! macro. After that, we use the version, author, and about methods to set this data using the corresponding macros. We can chain these method calls, because every method consumes and returns the updated App object. When we set meta-information about the application, we have to declare the supported arguments with the arg method.

To add an argument, we have to create an Arg instance with the with_name method, provide the name, and set extra parameters using chaining-of-methods calls. We can set a short form of the argument with the short method and the long form with the long method. You can set the name of the value for the generated documentation using the value_name method. You can provide a description of an argument using the  help method. The takes_value method is used to indicate that this argument requires a value. There is also a required method to indicate that an option is required, but we didn't use that here. All options are optional in our server.

We added the --address argument using these methods to set the address of the socket that we will use to bind the server. It also supports the short form a of the argument. We will read this value later.

The server will support the --config argument to set a configuration file. We have added this argument to the builder, but we will use it in the next section of this chapter.

After we create the builder, we call the get_matches method. This reads arguments with std::env::args_os and returns an ArgMatches instance, which we can use to get the values of the command-line parameters. We assign it to the matches local variable.

We should add the get_matches method before any logging call because it also prints help messages. We should avoid printing logs with the help description.
..................Content has been hidden....................

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