blob: 77fd0a1bfd17e17ceb20cf55ef1f9d7354287af8 (
plain) (
tree)
|
|
#[macro_use]
extern crate lazy_static;
use actix_web::{get, post, App, HttpResponse, HttpServer, Responder};
use base64;
use listenfd::ListenFd;
use regex::Regex;
lazy_static! {
static ref DATA_URI_RE: Regex =
Regex::new("^data:image/(?P<format>png|jpg|jpeg);base64,(?P<data>.+)").unwrap();
}
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hey, this is an API!")
}
#[post("/products")]
async fn create_product(req_body: String) -> impl Responder {
let caps = if let Some(c) = DATA_URI_RE.captures(&req_body) {
c
} else {
return HttpResponse::BadRequest().body("Invalid data URI");
};
let format = if let Some(f) = caps.name("format") {
f.as_str()
} else {
return HttpResponse::BadRequest().body("Invalid image format.");
};
let data = if let Some(d) = caps.name("data") {
d.as_str()
} else {
return HttpResponse::BadRequest().body("No encoded data.");
};
HttpResponse::Ok().body(format!("created\n{}\n{}", format, data))
}
#[get("/products")]
async fn get_products(_req_body: String) -> impl Responder {
HttpResponse::Ok().body("got product!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let mut listenfd = ListenFd::from_env();
let mut server = HttpServer::new(|| {
App::new()
.service(hello)
.service(create_product)
.service(get_products)
});
server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
server.listen(l)?
} else {
server.bind("127.0.0.1:8080")?
};
server.run().await
}
|