Skip to content

Instantly share code, notes, and snippets.

@KeenS

KeenS/Cargo.toml

Created Feb 21, 2020
Embed
What would you like to do?
[package]
name = "so-actix-web-reqwest"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "2.0"
reqwest = "0.10"
serde = "1.0"
use actix_web::{post, web, Error, HttpResponse};
use serde::Deserialize;
use std::fmt;
#[derive(Debug, Deserialize)]
pub struct MyError;
impl fmt::Display for MyError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Error")
}
}
pub struct Conn;
struct DbPool;
impl DbPool {
fn get(&self) -> Result<Conn, Error> {
Ok(Conn)
}
}
mod forms {
use serde::Deserialize;
#[derive(Deserialize)]
pub struct BackendForm {
pub name: String,
pub url: String,
}
}
mod actions {
use super::{Conn, MyError as Error};
use serde::Serialize;
#[derive(Serialize)]
pub struct Backend;
pub fn create_backend(
_name: &str,
_url: &str,
_version: &str,
_conn: &Conn,
) -> Result<Backend, Error> {
Ok(Backend)
}
}
fn main() {}
#[post("/backends")]
async fn add_backend(
pool: web::Data<DbPool>,
form: web::Json<forms::BackendForm>,
) -> Result<HttpResponse, Error> {
// 所有権エラーが出るので `format!` を使って結合する
let version = reqwest::get(&format!("{}/version", form.url))
.await
// map_errを使ってError型に変換可能な値に変換する。
// ここでは安直にInternalServerErrorを使う。
// もっと詳細にエラーを出したければ自分で定義した型を使うとよい。
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?
.text()
.await
// 同上
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
let conn = pool.get().expect("cant get db pool");
let backend =
web::block(move || actions::create_backend(&form.name, &form.url, &version, &conn))
.await
.map_err(|e| {
eprintln!("{}", e);
HttpResponse::InternalServerError().finish()
})?;
Ok(HttpResponse::Ok().json(backend))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment