Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0301· OpenAIAi2 WildChat-4.8M (AI2)

rust的axum中,我在某一个handler中如何一起使用State Json Extension

  1. User

    rust的axum中,我在某一个handler中如何一起使用State Json Extension

  2. Assistant

    在axum中,您可以在处理程序函数的参数列表中指定要使用的状态(使用State)和json数据(使用Json)。

    例如,下面的代码演示了如何在处理函数中同时使用State和Json:

    use axum::{Json, State};
    use serde::{Deserialize, Serialize};
    
    #[derive(Serialize, Deserialize)]
    struct User {
        id: u32,
        name: String,
    }
    
    async fn create_user(Json(user): Json<User>, State(app_state): State<AppState>) -> Json<User> {
        // Access the app state
        app_state.increment_users_created();
    
        // Create a new user
        let new_user = User {
            id: app_state.get_next_user_id(),
            name: user.name.clone(),
        };
    
        // Return the new user
        Json(new_user)
    }
    
    struct AppState {
        users_created: u32,
        next_user_id: u32,
    }
    
    impl AppState {
        fn increment_users_created(&mut self) {
            self.users_created += 1;
        }
    
        fn get_next_user_id(&mut self) -> u32 {
            let id = self.next_user_id;
            self.next_user_id += 1;
            id
        }
    }
    
    #[tokio::main]
    async fn main() {
        let app_state = State::new(AppState {
            users_created: 0,
            next_user_id: 1,
        });
    
        let app = route("/users", post(create_user)).app_data(app_state);
    
        // ...
    }
    

    在上面的代码中,我们定义了一个create_user函数,它将使用Json<User>和State<AppState>两个参数。Json参数用于接收上传的用户数据,而State参数用于访问我们定义的应用程序状态。

    在处理函数中,我们首先递增了AppState的users_created字段,然后创建了一个新用户,并返回了新用户的Json对象。

    在main函数中,我们定义了一个AppState状态并将其封装在State中,然后将其提供给应用程序。这样,我们可以确保在整个应用程序中共享应用程序状态。

    最后,我们将app路由提供给一个Axum服务器进行启动。