feat: add ability to customise welcome response by passing a filename
Diff
README.md | 3 ++-
src/config.rs | 1 +
src/main.rs | 32 ++++++++++++++++++++------------
3 files changed, 23 insertions(+), 13 deletions(-)
@@ -28,9 +28,10 @@ export LICENSE_API_BASE_URL="/"
export LICENSE_API_DATABASE="/path_to/your/license_database.yml"
export LICENSE_API_SERVER_IP="0.0.0.0"
export LICENSE_API_SERVER_PORT="8080"
export LICENSE_API_WELCOME_MESSAGE="/path/to/welcome.txt"
```
If `LICENSE_API_DATABASE` is not set, the server will refuse to start.
All environment variables except for `LICENSE_API_DATABASE` are optional. If `LICENSE_API_DATABASE` is not set, the server will refuse to start.
## License
@@ -14,6 +14,7 @@ pub struct ServerConfig {
pub server_ip: Ipv4Addr, #[serde(default = "ServerConfig::default_server_port")]
pub server_port: u16,
pub welcome_message: Option<String>
}
impl ServerConfig {
@@ -80,22 +80,30 @@ fn build_response(status: StatusCode, data: String) -> Response {
}
async fn get_welcome_message(req: tide::Request<RunningConfig>) -> tide::Result<Response> {
let base_url = req.state().config.base_url.as_str();
match &req.state().config.welcome_message {
Some(file) => match async_std::fs::read_to_string(file).await {
Ok(data) => return Ok(build_response(StatusCode::Ok, data)),
Err(_) => {
log::error!("Unable to read welcome message file.");
return Ok(build_response(StatusCode::Ok, build_welcome_message(req)));
}
},
None => return Ok(build_response(StatusCode::Ok, build_welcome_message(req))),
}
}
fn build_welcome_message(req: tide::Request<RunningConfig>) -> String {
let base_url = req.state().config.base_url.clone();
let header = String::from("Available endpoints:");
let base = format!("{}", base_url);
let list = format!("{}list", base_url);
let all = format!("{}list/full", base_url);
let license = format!("{}<license>", base_url);
Ok(build_response(
StatusCode::Ok,
format!(
"{}\n {}\n {}\n {}\n {}",
header, base, list, all, license
)
.to_string(),
))
format!(
"{}\n {}\n {}\n {}\n {}",
header, base, list, all, license
)
}
async fn get_fallback_response(req: tide::Request<RunningConfig>) -> tide::Result<Response> {
@@ -128,7 +136,7 @@ async fn get_requested_license(req: tide::Request<RunningConfig>) -> tide::Resul
let request = req.url().path().strip_prefix("/").unwrap_or("");
let response = match req.state().database.get_license(request) {
Some(license) => {