其他
用 Rust 程序和 Webase 交互 | Rust 学习笔记(四)
The following article is from 李大狗Leeduckgo Author 李大狗就是我
https://webasedoc.readthedocs.io/zh_CN/latest/docs/WeBASE-Front/index.html
Reqwest 这个 Rust Http 库的使用 Lib 的编写与使用
cargo new webase-interactor-example
在这次学习中,我们引入更复杂的项目结构,我们会在项目中创建一个 Lib 并引用它,做到模块解耦。
cd webase-interactor-example
cargo new webase-interactor --lib
.
├── Cargo.toml
├── src
│ └── main.rs
└── webase-interactor
├── Cargo.toml
└── src
├── chain.rs
└── lib.rs
3.编写 webase-interactor 库
3.1 编写 webase-interactor 的 Cargo.toml
webase-interactor
的Cargo.toml
如下:
[package]
name = "webase-interactor"
version = "0.1.0"
authors = ["leeduckgo <albertschr@163.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
reqwest = { version = "0.10", features = ["blocking", "json"] }
tokio = { version = "0.2", features = ["full"] }
我们在此引入了reqwest
这个HTTP
库。
An ergonomic, batteries-included HTTP Client for Rust. https://github.com/seanmonstar/reqwest
3.2 编写 chain.rs
chain.rs
的内容如下:pub struct Chain{
ip: String,
}
impl Chain{
pub fn new(ip: String) -> Chain {
Chain { ip }
}
pub fn get_ip(&self) -> String {
self.ip.to_string()
}
pub fn get_block_number(&self) -> Result<String, reqwest::Error>{
let mut url =self.ip.to_string();
url += &"WeBASE-Front/1/web3/blockNumber/".to_string();
let resp =
reqwest::blocking::get(&url)?
// .await?
.text();
// .await?;
resp
}
}
3.2.1 结构体
https://www.runoob.com/rust/rust-struct.html https://kaisery.github.io/trpl-zh-cn/ch05-01-defining-structs.html
struct Rectangle {
width: u32,
height: u32,
}
3.2.2 结构体方法
impl Rectangle {
fn area(&self) -> u32 {
self.width * self.height
}
}
new 方法:创建一个新的 Chain。
get_ip 方法:获取 Chain 实例的 IP。
get_block_number 方法:通过和 Webase 交互,获取当前块高。
pub fn get_block_number(&self) -> Result<String, reqwest::Error>{ //注意不要遗漏 &self
// do sth
resp // 在 rust 中,我们无需return关键字,最后一行不带;,执行的结构即函数返回值。
}
3.3 编写lib.rs
lib.rs
内容如下:
//! # WeBase
//!
//! A library to interact with webase.
#![warn(unused_extern_crates)]
pub mod chain;
pub use self::chain::*;
// phrases.rs
pub mod english {
pub mod greetings {
pub fn hello() {
println!("Hello!")
}
pub fn hey_guies() {
println!("Hey, guies!")
}
}
pub mod farewells {
pub fn goodbye() {
println!("Goodbye!")
}
pub fn see_you() {
println!("See you!")
}
}
}
pub mod chinese {
pub mod greetings {
pub fn hello() {
println!("你好!")
}
pub fn have_eaten() {
println!("吃了么?")
}
}
pub mod farewells {
pub fn goodbye() {
println!("再见!")
}
pub fn everyone_will_know_you() {
println("天下谁人不识君!")
}
}
}
4.完成主项目
4.1 编写 Cargo.toml
[package]
name = "webase-interactor-example"
version = "0.1.0"
authors = ["leeduckgo <albertschr@163.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
pretty_env_logger = "0.3"
log = "0.4"
reqwest = { version = "0.10", features = ["json"] }
tokio = { version = "0.2", features = ["full"] }
webase-interacter = { path="./webase-interactor", version = "0.1.0"}
webase-interactor
。4.2 编写 main.rs
main.rs
的内容如下:
extern crate pretty_env_logger;
use webase_interactor::Chain;
#[macro_use] extern crate log;
fn main(){
pretty_env_logger::init();
print_block_number();
}
pub fn print_block_number() {
let ip = "http://127.0.0.1:5002/".to_string();
let chain = Chain::new(ip);
let res = chain.get_block_number();
match res {
Err(e) => {
println!("error: {}", e);
}
Ok(b_number) => {
info!("last block height: {}", b_number);
}
}
}
cargo build
https://github.com/leeduckgo/RustStudy