You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
2.8 KiB
88 lines
2.8 KiB
#![feature(async_closure)]
|
|
|
|
use std::collections::HashMap;
|
|
use std::fs::File;
|
|
use std::io::Read;
|
|
use lambda_http::{run, service_fn, Error, Request, RequestExt, Response};
|
|
use namegen::Name;
|
|
use serde::{Deserialize};
|
|
|
|
type EndpointResult = Result::<Response<String>, Error>;
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<(), Error> {
|
|
tracing_subscriber::fmt()
|
|
.with_max_level(tracing::Level::INFO)
|
|
// disable printing the name of the module in every log line.
|
|
.with_target(false)
|
|
// disabling time is handy because CloudWatch will add the ingestion time.
|
|
.without_time()
|
|
.init();
|
|
|
|
let mut file = File::open("names.json").unwrap();
|
|
let mut data = String::new();
|
|
file.read_to_string(&mut data).unwrap();
|
|
|
|
let json = serde_json::from_str::<NameGeneratorData>(&data).unwrap();
|
|
let json_ref = &json;
|
|
|
|
run(service_fn(move |event: Request| async move {
|
|
let path = event.raw_http_path();
|
|
let keys: Vec<String> = path.split('/').filter(|f| !f.is_empty()).map(|f| f.into()).collect();
|
|
|
|
let key = if let Some(key) = keys.get(1) {
|
|
key.clone()
|
|
} else {
|
|
return EndpointResult::Ok(
|
|
Response::builder()
|
|
.status(400)
|
|
.header("content-type", "text/plain")
|
|
.body("Missing path".into())
|
|
.expect("failed to render response")
|
|
)
|
|
};
|
|
|
|
if let Some(name) = json_ref.map.get(&key) {
|
|
let format_name = if let Some(key) = keys.get(2) {
|
|
key.as_str()
|
|
} else {
|
|
name.first_format_name().unwrap()
|
|
};
|
|
|
|
if let Some(gen) = name.generate(format_name) {
|
|
let vec: Vec<String> = gen.take(64).collect();
|
|
|
|
EndpointResult::Ok(
|
|
Response::builder()
|
|
.status(200)
|
|
.header("content-type", "application/json")
|
|
.body(serde_json::to_string(&vec).unwrap().into())
|
|
.expect("failed to render response")
|
|
)
|
|
} else {
|
|
EndpointResult::Ok(
|
|
Response::builder()
|
|
.status(404)
|
|
.header("content-type", "text/plain")
|
|
.body("Format not found".into())
|
|
.expect("failed to render response")
|
|
)
|
|
}
|
|
} else {
|
|
EndpointResult::Ok(
|
|
Response::builder()
|
|
.status(404)
|
|
.header("content-type", "text/plain")
|
|
.body("Generator not found".into())
|
|
.expect("failed to render response")
|
|
)
|
|
}
|
|
})).await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct NameGeneratorData {
|
|
map: HashMap<String, Name>,
|
|
}
|