Origin [Rust] Actix Web 中使用protobuf完成前后端交互

2022-10-31 12:06:37 浏览数 (1)

参考:

https://github.com/x931890193/rust_blog

代码语言:javascript复制
# Cargo.toml
[package]
name = "rust_blog"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-protobuf = "0.8"
actix-web = "4"
chrono = { version = "0.4", features = ["serde"] }
diesel = { version = "2.0.0", features = ["r2d2", "postgres"] }
dotenvy = "0.15"
env_logger = "0.9"
futures-util = { version = "0.3.17", default-features = false, features = ["std"] }
json = "0.12"
log = "0.4"
prost = { version = "0.10.4", default-features = false, features = ["prost-derive"] }

protobuf = { version = "3.1", features = ["with-bytes"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[build-dependencies]
protobuf-codegen = { version = "3.1" }
prost-build = "0.5"
代码语言:javascript复制
// build.rs
fn main() {
    // std::fs::create_dir_all("src/proto").unwrap();
    // protobuf_codegen::Codegen::new()
    //     // .pure()
    //     .out_dir("src/proto")
    //     .inputs(&["proto/pb.proto"])
    //     .include("proto")
    //     .customize(
    //         protobuf_codegen::Customize::default()
    //             .tokio_bytes(true)
    //     )
    //     .run()
    //     .expect("Codegen failed.");

    prost_build::Config::new()
        .out_dir("src/proto")
        .compile_protos(&["src/proto/pb.proto"], &["src/proto"])
        .unwrap();
}
代码语言:javascript复制
use actix_protobuf::{ProtoBufResponseBuilder as _};
use actix_web::{HttpResponse, Result};
use serde::{Deserialize, Serialize};
use chrono::{Local};
use crate::proto::pb;


#[derive(Debug, Serialize, Deserialize)]
struct Greet {
    msg: String,
    server_time: String,
}

/// This is index handler
pub async fn index() -> HttpResponse {
    let fmt = "%Y年%m月%d日 %H:%M:%S";
    let resp = Greet{
        msg : String::from("rust_blog"),
        server_time: Local::now().format(fmt).to_string().to_owned()
    };
    HttpResponse::Ok().json(resp) // <- send response
}
// 这里是protobuf 返回数据
pub async fn base_resp() -> Result<HttpResponse> {
    let base = pb::BaseResp{ code: 111111, msg: "111111111".to_string() };
    HttpResponse::Ok().protobuf(base)
}
web

0 人点赞