diff --git a/examples/hello-world/main.rs b/examples/hello-world/main.rs index 6572dd3f..13309316 100644 --- a/examples/hello-world/main.rs +++ b/examples/hello-world/main.rs @@ -2,7 +2,6 @@ use async_std::sync::RwLock; use futures::FutureExt; use serde::{Deserialize, Serialize}; use snafu::Snafu; -use std::fs; use std::io; use tide_disco::{http::StatusCode, Api, App, Error, RequestError}; use tracing::info; @@ -37,10 +36,8 @@ async fn serve(port: u16) -> io::Result<()> { let mut app = App::<_, HelloError>::with_state(RwLock::new("Hello".to_string())); app.with_version(env!("CARGO_PKG_VERSION").parse().unwrap()); - let mut api = Api::, HelloError>::new(toml::from_slice(&fs::read( - "examples/hello-world/api.toml", - )?)?) - .unwrap(); + let mut api = + Api::, HelloError>::from_file("examples/hello-world/api.toml").unwrap(); api.with_version(env!("CARGO_PKG_VERSION").parse().unwrap()); // Can invoke by browsing diff --git a/src/api.rs b/src/api.rs index 86206d7b..f0120d00 100644 --- a/src/api.rs +++ b/src/api.rs @@ -30,7 +30,9 @@ use serde_with::{serde_as, DisplayFromStr}; use snafu::{OptionExt, ResultExt, Snafu}; use std::collections::hash_map::{Entry, HashMap, IntoValues, Values}; use std::fmt::Display; +use std::fs; use std::ops::Index; +use std::path::Path; use tide::http::content::Accept; /// An error encountered when parsing or constructing an [Api]. @@ -47,6 +49,7 @@ pub enum ApiError { MissingFormatVersion, InvalidFormatVersion, AmbiguousRoutes { route1: String, route2: String }, + CannotReadToml { reason: String }, } /// Version information about an API. @@ -178,6 +181,18 @@ impl Api { }) } + /// Create an [Api] by reading a TOML specification from a file. + pub fn from_file>(path: P) -> Result { + Self::new( + toml::from_slice(&fs::read(path).map_err(|err| ApiError::CannotReadToml { + reason: err.to_string(), + })?) + .map_err(|err| ApiError::CannotReadToml { + reason: err.to_string(), + })?, + ) + } + /// Iterate over groups of routes with the same path. pub fn routes_by_path(&self) -> impl Iterator)> { self.routes_by_path.iter().map(|(path, routes)| {