feat: add server config via environment variables
Diff
Cargo.toml | 3 +++
README.md | 30 ++++++++++++++++++++++++++++++
src/main.rs | 50 ++++++++++++++++++++++++++++++++++++++++++++------
3 files changed, 77 insertions(+), 6 deletions(-)
@@ -7,4 +7,7 @@ edition = "2021"
[dependencies]
async-std = { version = "1.12.0", features = ["attributes"] }
envy = "0.4.2"
jealousy = { version = "0.1.5", features = ["derive"] }
serde = { version = "1.0.188", features = ["derive"] }
tide = "0.16.0"
@@ -2,6 +2,36 @@
A drop-in Rust implementation of [my old open source license api](https://git.holly.sh/license-api.git) that was written in PHP.
## Usage
```
LICENSE_API_DATABASE="/path_to/your/license_database.yml"
cargo build
cargo run
curl 0.0.0.0:8080/
curl 0.0.0.0:8080/list
curl 0.0.0.0:8080/list/full
curl 0.0.0.0:8080/<license>
```
## Configuration
The server by default will run on `0.0.0.0:8080` with a base URL of `/`
There is no default database set.
Configuration is done through environment variables.
```shell
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"
```
If `LICENSE_API_DATABASE` is not set, the server will refuse to start.
## License
- [AGPL 3.0](LICENSE)
@@ -1,20 +1,58 @@
use std::net::Ipv4Addr;
use serde::Deserialize;
use jealousy::FromEnv;
use tide::{http::mime, log, Response, Result, Server, StatusCode};
const BASE_URL: &str = "/api";
#[derive(Debug, Deserialize, FromEnv)]
#[from_env(prefix = "LICENSE_API")]
struct Config {
#[serde(default = "Config::default_base_url")]
base_url: String,
database: String,
#[serde(default = "Config::default_server_ip")]
server_ip: Ipv4Addr, #[serde(default = "Config::default_server_port")]
server_port: u16,
}
impl Config {
fn default_base_url() -> String {
String::from("/")
}
fn default_server_ip() -> Ipv4Addr {
Ipv4Addr::new(0, 0, 0, 0)
}
fn default_server_port() -> u16 {
8080
}
}
#[async_std::main]
async fn main() -> Result<()> {
let mut app = tide::new();
log::start();
create_routes(&mut app);
let config = Config::from_env();
match config {
Ok(config) => {
let mut app = tide::new();
create_routes(&mut app, &config);
app.listen(format!("{}:{}", config.server_ip, config.server_port))
.await?;
}
Err(_) => (), }
app.listen("127.0.0.1:8080").await?;
Ok(())
}
fn create_routes(server: &mut Server<()>) {
let mut base_route = server.at(BASE_URL);
fn create_routes(server: &mut Server<()>, config: &Config) {
let mut base_route = server.at(&config.base_url);
base_route.get(get_welcome_message);
base_route.at(":license").get(get_requested_license);