前言
最近打算熟悉下rust,先使用tcp stream+protobuf寫個簡單的TLV服務(wù)者吁。發(fā)現(xiàn)rust處理生成代碼的方式和go還有點(diǎn)不一樣刀闷。比較符合rust的做法是寫個build.rs腳本根时。
protobuf 配置
protobuf 是google開發(fā)的協(xié)議序列化,反序列化器垛耳,具備很高的性能栅屏。在內(nèi)網(wǎng)的rpc通信中比較流行。message 定義數(shù)據(jù)結(jié)構(gòu)用的堂鲜,rfc定義應(yīng)用層的數(shù)據(jù)包使用message術(shù)語栈雳,所以protobuf取名還是挺講究的。
syntax = "proto3";
message HotWordRequest {
string hot_word_text=1;
string session_id = 2;
}
message HotWordResponse {
int64 errcode = 1;
string errmsg = 2;
string session_id = 3;
bytes hot_word_model=4;
}
build.rs內(nèi)容
fn main() {
protobuf_codegen_pure::Codegen::new()
.out_dir("src/protos")
.inputs(&["protos/small-model.proto"])
.include("protos")
.run()
.expect("Codegen failed.");
}
依賴配置
rust 里面使用toml格式配置依賴缔莲,toml是一種很基礎(chǔ)和廣泛使用的配置文件格式哥纫,toml格式比較簡單,一個比較基礎(chǔ)的解析器用c可能40行可以實(shí)現(xiàn)痴奏。比較好奇的是為什么不使用yaml蛀骇?唯一能想到的是,可能是想大家的依賴配置玩的不要那么花哨读拆。
[build-dependencies]
protobuf-codegen-pure = "2.14"
運(yùn)行命令
cargo build運(yùn)行如果沒有報錯就大功告成擅憔。
cargo build
最后的目錄結(jié)構(gòu)
.
├── build.rs
├── Cargo.toml
├── protos
│ └── small-model.proto
└── src
├── main.rs
└── protos
└── small_model.rs