rust-shop是使用rust语言开发的微信商城(商城功能开发中),内含web开发框架,使用简单,可扩展。
#[route("POST", "/hello")]
pub async fn hello(RequestParam(user): RequestParam<String>)-> anyhow::Result<String>{
let u = user.clone();
Ok(format!("hello {}",u))
}
上面的代码匹配的请求为: POST /hello?user=pgg
#[route("POST", "/hello")]
pub async fn hello(sql_exe_with_tran: &mut SqlCommandExecutor<'_, '_>)-> anyhow::Result<String>{
Ok(String::from("hello"))
}
如果不想使用事务,只需将sql_exe_with_tran参数名改为sql_exe即可
let mut security_config = WebSecurityConfigurer::new();
security_config.enable_security(false);
security_config.authentication_token_resolver(AuthenticationTokenResolverFn::from(Box::new(
|| -> Box<dyn AuthenticationTokenResolver + Send + Sync> {
Box::new(UsernamePasswordAuthenticationTokenResolver {})
},
)));
security_config.password_encoder(Box::new(Sha512PasswordEncoder));
security_config.load_user_service(LoadUserServiceFn::from(Box::new(
|_req: &mut RequestCtx| -> Box<
dyn for<'r, 'c, 'd> Fn(
&'r mut SqlCommandExecutor<'c, 'd>,
) -> Box<(dyn LoadUserService + Send + Sync + 'r)>
+ Send
+ Sync,
> { Box::new(load_user_service_fn) },
)));
srv.security_config(security_config);
#[route("GET", "model_and_view")]
pub async fn model_and_view(ctx: &mut RequestCtx) -> anyhow::Result<ModelAndView> {
let mut model_and_view = ModelAndView::new("test.html".to_string());
let user = User {
id: 0,
name: "pgg".to_string(),
is_auth: false,
};
model_and_view.insert("user", &user);
ctx.session.insert_or_update("user".to_string(), &user);
Ok(model_and_view)
}
#[tokio::main]
#[rust_shop_macro::scan_route("/src")]
async fn main() -> anyhow::Result<()> {
log4rs::init_file("log4rs.yaml", Default::default()).unwrap();
info!("booting up");
let addr: SocketAddr = format!("127.0.0.1:{}", &APP_CONFIG.server.port)
.parse()
.unwrap();
let mut srv = Server::new();
srv.filter(AuthenticationFilter);
srv.filter(AccessLogFilter);
srv.filter(AuthenticationProcessingFilter);
srv.filter(SecurityInterceptor);
let conn_pool = mysql_connection_pool().await?;
srv.extension(State::new(conn_pool.clone()));
let mut security_config = WebSecurityConfigurer::new();
security_config.enable_security(false);
security_config.authentication_token_resolver(AuthenticationTokenResolverFn::from(Box::new(
|| -> Box<dyn AuthenticationTokenResolver + Send + Sync> {
Box::new(UsernamePasswordAuthenticationTokenResolver {})
},
)));
security_config.password_encoder(Box::new(Sha512PasswordEncoder));
security_config.load_user_service(LoadUserServiceFn::from(Box::new(
|_req: &mut RequestCtx| -> Box<
dyn for<'r, 'c, 'd> Fn(
&'r mut SqlCommandExecutor<'c, 'd>,
) -> Box<(dyn LoadUserService + Send + Sync + 'r)>
+ Send
+ Sync,
> { Box::new(load_user_service_fn) },
)));
srv.security_config(security_config);
srv.run(addr).await.unwrap();
info!("server shutdown!");
Ok(())
}