Rust:axum学习笔记(2) response

本文介绍Rust Web框架Axum中的响应处理方式,演示了多种不同类型的响应返回示例,包括纯文本、HTML、JSON等,并展示了如何处理自定义错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Rust:axum学习笔记(2) response

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

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

1

2

3

4

5

axum = "0.4.3"

tokio = { version="1", features = ["full"] }

serde = { version="1", features = ["derive"] }

serde_json = "1"

http = "0.2.1"

这是依赖项,下面的代码主要来自官方文档,在此基础上补充了中文及“自定义错误”及“自定义结构”的返回示例(包括了web开发中大部分的常用返回格式)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

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<u8> {

    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<&'static str> {

    Html("<h1>Hello, World!</h1>")

}

// `Json` gives a content-type of `application/json` and works with any type

// that implements `serde::Serialize`

async fn json() -> Json<Value> {

    Json(json!({ "data": 42 }))

}

// `Result<T, E>` where `T` and `E` implement `IntoResponse` is useful for

// returning errors

async fn result() -> Result<&'static str, StatusCode> {

    Ok("all good")

}

// `Response` gives full control

async fn response() -> Response<Body> {

    Response::builder().body(Body::empty()).unwrap()

}

#[derive(Serialize)]

struct Blog {

    title: String,

    author: String,

    summary: String,

}

async fn blog_struct() -> Json<Blog> {

    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<Blog>) {

    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<&'static str, CustomError> {

    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();

}

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

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

1

2

3

4

5

6

7

8

9

10

11

12

13

use axum::{

    routing::get, Router,http::header::{HeaderMap,HeaderValue,HeaderName}

};

use std::fs::*;

async fn image() -> (HeaderMap, Vec<u8>) {

    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())

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值