Rust:axum学习笔记(2) response

上一篇的hello world里,示例过于简单,仅仅只是返回了一个字符串,实际上axum的response能返回各种格式,包括:

plain_text
html
json
http StatusCode

web开发中需要的各种格式,都能返回。talk is cheap ,show me the code! 直接上代码:

bash;gutter:true; axum = "0.4.3" tokio = { version="1", features = ["full"] } serde = { version="1", features = ["derive"] } serde_json = "1" http = "0.2.1"</p> <pre><code> 这是依赖项,下面的代码主要来自[官方文档](https://docs.rs/axum/0.2.8/axum/#building-responses),在此基础上补充了中文及"自定义错误"及"自定义结构"的返回示例(包括了web开发中大部分的常用返回格式) ;gutter:true;
use axum::{
body::{self,Body},
http::header::{HeaderMap, HeaderName, HeaderValue},
response::{Headers, Html, IntoResponse, Json,Response},
routing::get,
Router,
};
use http::{ StatusCode, Uri};
use serde::Serialize;
use serde_json::{json, Value};

// We’ve already seen returning &’static str
async fn plain_text() -> &’static str {
"foo"
}

// String works too and will get a text/plain; charset=utf-8 content-type
async fn plain_text_string(uri: Uri) -> String {
format!("Hi from {}", uri.path())
}

// Bytes will get a application/octet-stream content-type
async fn bytes() -> Vec {
vec![1, 2, 3, 4]
}

// () gives an empty response
async fn empty() {}

// StatusCode gives an empty response with that status code
async fn empty_with_status() -> StatusCode {
StatusCode::NOT_FOUND
}

// A tuple of StatusCode and something that implements IntoResponse can
// be used to override the status code
async fn with_status() -> (StatusCode, &’static str) {
(StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong")
}

// A tuple of HeaderMap and something that implements IntoResponse can
// be used to override the headers
async fn with_headers() -> (HeaderMap, &’static str) {
let mut headers = HeaderMap::new();
headers.insert(
HeaderName::from_static("x-foo"),
HeaderValue::from_static("foo"),
);
(headers, "foo")
}

// You can also override both status and headers at the same time
async fn with_headers_and_status() -> (StatusCode, HeaderMap, &’static str) {
let mut headers = HeaderMap::new();
headers.insert(
HeaderName::from_static("x-foo"),
HeaderValue::from_static("foo"),
);
(StatusCode::INTERNAL_SERVER_ERROR, headers, "foo")
}

// Headers makes building the header map easier and impl Trait is easier
// so you don’t have to write the whole type
async fn with_easy_headers() -> impl IntoResponse {
Headers(vec![("x-foo", "foo")])
}

// Html gives a content-type of text/html
async fn html() -> Html {
Html("Hello, World!")
}

// Json gives a content-type of application/json and works with any type
// that implements serde::Serialize
async fn json() -> Json {
Json(json!({ "data": 42 }))
}

// Result where T and E implement IntoResponse is useful for
// returning errors
async fn result() -> Result {
Ok("all good")
}

// Response gives full control
async fn response() -> Response {
Response::builder().body(Body::empty()).unwrap()
}

#[derive(Serialize)]
struct Blog {
title: String,
author: String,
summary: String,
}

async fn blog_struct() -> Json {
let blog = Blog {
title: "axum笔记(2)-response".to_string(),
author: "菩提树下的杨过".to_string(),
summary: "response各种示例".to_string(),
};
Json(blog)
}

async fn blog_struct_cn() -> (HeaderMap, Json) {
let blog = Blog {
title: "axum笔记(2)-response".to_string(),
author: "菩提树下的杨过".to_string(),
summary: "response各种示例".to_string(),
};

let mut headers = HeaderMap::new();
headers.insert(
HeaderName::from_static("content-type"),
HeaderValue::from_static("application/json;charset=utf-8"),
);
(headers, Json(blog))
}

struct CustomError {
msg: String,
}

impl IntoResponse for CustomError {

fn into_response(self) -> Response {
let body= body::boxed(body::Full::from(self.msg));
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(body)
.unwrap()
}
}

async fn custom_error() -> Result {
Err(CustomError {
msg: "Opps!".to_string(),
})
}

#[tokio::main]
async fn main() {
// our router
let app = Router::new()
.route("/plain_text", get(plain_text))
.route("/plain_text_string", get(plain_text_string))
.route("/bytes", get(bytes))
.route("/empty", get(empty))
.route("/empty_with_status", get(empty_with_status))
.route("/with_status", get(with_status))
.route("/with_headers", get(with_headers))
.route("/with_headers_and_status", get(with_headers_and_status))
.route("/with_easy_headers", get(with_easy_headers))
.route("/html", get(html))
.route("/json", get(json))
.route("/result", get(result))
.route("/response", get(response))
.route("/blog", get(blog_struct))
.route("/blog_cn", get(blog_struct_cn))
.route("/custom_error", get(custom_error));

// run it with hyper on localhost:3000
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}

Rust:axum学习笔记(2) response

部分url的访问效果如上图,其它的就留给朋友们自己去尝试吧。注:网上传说的中文乱码问题,0.4.3新版本并没有出现,输出时已经自带了chatset=utf-8。

Rust:axum学习笔记(2) response

最后再补1个返回图片的示例:

cpp;gutter:true; use axum::{ routing::get, Router,http::header::{HeaderMap,HeaderValue,HeaderName} }; use std::fs::*;</p> <p>async fn image() -> (HeaderMap, Vec) { let mut headers = HeaderMap::new(); headers.insert( HeaderName::from_static("content-type"), HeaderValue::from_static("image/png"), ); (headers, read(String::from("/Users/Downloads/avatar.png")).unwrap()) }

参考链接:

https://docs.rs/axum/0.4.3/axum/response/trait.IntoResponse.html

https://docs.rs/axum/0.2.8/axum/#building-responses

Original: https://www.cnblogs.com/yjmyzz/p/axum_tutorial_2_response.html
Author: 菩提树下的杨过
Title: Rust:axum学习笔记(2) response

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/546619/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 面向对象ooDay1

    如何创建类?如何创建对象?如何访问成员? package ooday01; //学生类 public class Student { //成员变量—-对象的属性 String …

    技术杂谈 2023年7月11日
    099
  • 设计模式-组合模式

    类型:结构型 目的:将对象集合组合成 树形结构,使客户端可以以 一致的方式处理 单个对象(叶子节点)和 *组合对象(根节点) 话不多说,上优化案例。 优化案例 不使用组合模式。现有…

    技术杂谈 2023年7月11日
    082
  • 老生常谈系列之Aop–Aop的经典应用之Spring的事务实现分析(三)

    上一篇文章老生常谈系列之Aop–Aop的经典应用之Spring的事务实现分析(二)从三个问题导入,分析了Spring是如何开启事务的、Spring是如何为需要事务支持的…

    技术杂谈 2023年7月25日
    088
  • 基础篇:JAVA集合,面试专用

    没啥好说的,在座的各位都是靓仔 List 数组 Vector 向量 Stack 栈 Map 映射字典 Set 集合 Queue 队列 Deque 双向队列 关注公众号,一起交流,微…

    技术杂谈 2023年7月25日
    0117
  • 传输中文的乱码的原因及解决方式(两次encodeURI())转码;

    .encodeURL函数主要是来对URI来做转码,它默认是采用的UTF-8的编码. . UTF-8编码的格式:一个汉字来三个字节构成,每一个字节会转换成16进制的编码,同时添加上%…

    技术杂谈 2023年6月1日
    0107
  • 常用开发工具的安装和使用

    常用开发工具的安装和使用 IntelliJ IDEA的安装和使用 安装教程 1.教育优惠 JetBrains开发的众多开发工具提供教育优惠,可以方便在校学生使用。通过学校提供的教育…

    技术杂谈 2023年7月23日
    0101
  • GIT使用说明

    1、Git入门教程 1.1:Git入门与使用 (一) Git介绍与安装 1.2:Git入门与使用 (二) Git相关命令的介绍与使用 1.3:Git入门与使用 (三) 使用GitH…

    技术杂谈 2023年6月21日
    0110
  • ruoyi接口权限校验

    此文章属于ruoyi项目实战系列 ruoyi系统在前端主要通过权限字符包含与否来动态显示目录和按钮。为了防止通过http请求绕过权限限制,后端接口也需要进行相关权限设计。 @Pre…

    技术杂谈 2023年6月21日
    0126
  • springboot自定义拦截器

    1、创建拦截类 @Configuration public class InterceptorAdapterConfig implements WebMvcConfigurer {…

    技术杂谈 2023年7月25日
    0106
  • VLC搭建RTSP服务器

    实时流协议 RTSP 是在实时传输协议的基础上工作的,主要实现对多媒体播放的控制。用户对多媒体信息的播放、暂停、前进和后退等功能就是通过对实时数据流的控制来实现的。 而这些播放控制…

    技术杂谈 2023年5月31日
    0101
  • LLVM编译技术应用分析

    LLVM编译技术应用分析 参考文献链接 https://mp.weixin.qq.com/s/_d5HR9yHdwhGYozr9IaU_A https://mp.weixin.qq…

    技术杂谈 2023年5月31日
    0120
  • graylog server 模块说明一 入口简单说明

    protected void startCommand() { final AuditEventSender auditEventSender = injector.getInst…

    技术杂谈 2023年5月30日
    098
  • 针对“RuntimeError: each element in list of batch should be of equal size” 问题解决

    第一次运行代码出现了这个问题:这个问题的出现主要来源于DataLoader类中的collate.py文件造成的问题,由于每个batch里的长度不一致,因此导致出现了该问题。通过百度…

    技术杂谈 2023年7月25日
    0142
  • 《鹿柴》王维

    《鹿柴》王维 空山不见人,但闻人语响。 返景入深林,复照青苔上。 posted @2022-08-01 08:20 郑瀚Andrew 阅读(503 ) 评论() 编辑 Origin…

    技术杂谈 2023年5月31日
    0117
  • nmake

    http://t.zoukankan.com/liangxiaofeng-p-3247968.html Original: https://www.cnblogs.com/hshy…

    技术杂谈 2023年5月31日
    0124
  • 装饰器

    装饰器(Decorators)是修改其它函数功能的 函数。 (1)函数中可以定义函数 def fun(): def inner(): print("This is a i…

    技术杂谈 2023年7月11日
    090
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球