前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Origin [Rust] Actix Web 中使用protobuf完成前后端交互

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

作者头像
用户2458545
发布2022-10-31 12:06:37
5470
发布2022-10-31 12:06:37
举报
文章被收录于专栏:阿牛的牙
[Rust] Actix Web 中使用protobuf完成前后端交互
[Rust] Actix Web 中使用protobuf完成前后端交互

参考:

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)
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022年10月22日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 参考:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档