CLI tools & HTTP clients
12 steps in 4 sets of Rust.
Rust makes very good command-line tools, and this is why people who do not write systems software end up learning it anyway. Argument parsing with clap, then reading and writing streams properly.
The last set is reqwest for HTTP. Twelve steps, and the Encore is a tool you could plausibly install and use.
Arguments
- Arguments the plain wayBefore any crate: std::env gives you the arguments and the environment.
- clap's derive APIA struct with attributes becomes a parser, a help text and a version flag.
- Flags, counts and listsOptional values, repeated flags, and arguments that take many values.
- SubcommandsOne binary, several verbs: an enum of subcommands, each with its own args.
- Validating argumentsclap can enforce ranges, enumerations and required combinations before main runs.
Input & output
- Reading standard inputA filter reads lines from stdin, so it composes with every other tool.
Requests with reqwest
- An HTTP GETreqwest's async client: send the request, await the body.
- Typed JSON responsesAsk for JSON and reqwest deserializes straight into your type.
- Posting a bodyA POST with JSON, headers and a bearer token, built up on the request.
- Status codes and failuresA 404 is a successful request with an unsuccessful status — handle both.
- Reusing a clientOne Client, configured once: connection pooling, timeouts, default headers.
Encore
- fetch_tours.rsA real CLI: clap parses the flags, reqwest fetches, serde models the reply.