24 releases

0.4.0-alpha.8 Apr 24, 2024
0.4.0-alpha.3 Mar 17, 2024
0.2.1 Nov 23, 2022
0.1.4 Jul 27, 2022

#895 in Web programming

Download history 1/week @ 2024-02-02 8/week @ 2024-02-09 31/week @ 2024-02-16 56/week @ 2024-02-23 239/week @ 2024-03-01 44/week @ 2024-03-08 229/week @ 2024-03-15 40/week @ 2024-03-22 85/week @ 2024-03-29 34/week @ 2024-04-05 2/week @ 2024-04-12 368/week @ 2024-04-19 52/week @ 2024-04-26 4/week @ 2024-05-03

426 downloads per month
Used in fire-http-codegen

MIT/Apache

185KB
5.5K SLoC

crates.io docs.rs

Make web apis.

Features

  • stream

Example

# use fire_http_api as api;
use std::fmt;
use std::sync::{Arc, Mutex};

use api::{Request, Method};
use api::error::{self, Error as ApiError, StatusCode};
use api::{fire, api};
use fire::impl_res_extractor;

use serde::{Serialize, Deserialize};


// -- Type definitions

#[derive(Debug, Clone, Serialize)]
pub enum Error {
	Internal(String),
	Request(String)
}

impl error::ApiError for Error {
	fn from_error(e: ApiError) -> Self {
		match e {
			ApiError::HeadersMissing(_) |
			ApiError::Deserialize(_) => {
				Self::Request(e.to_string())
			}
			e => Self::Internal(e.to_string()),
		}
	}

	fn status_code(&self) -> StatusCode {
		match self {
			Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
			Self::Request(_) => StatusCode::BAD_REQUEST
		}
	}
}

impl fmt::Display for Error {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		fmt::Debug::fmt(self, f)
	}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct NameReq;

#[derive(Debug, Clone, Serialize, Deserialize)]
struct Name {
	firstname: String,
	lastname: String
}

impl Request for NameReq {
	type Response = Name;
	type Error = Error;

	const PATH: &'static str = "/name";
	const METHOD: Method = Method::GET;
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct SetNameReq {
	name: Name
}

impl Request for SetNameReq {
	type Response = ();
	type Error = Error;

	const PATH: &'static str = "/name";
	const METHOD: Method = Method::PUT;
}

// -- implementations

struct SharedName(Mutex<Name>);

impl_res_extractor!(SharedName);

#[api(NameReq)]
fn get_name(req: NameReq, name: &SharedName) -> Result<Name, Error> {
	let lock = name.0.lock().unwrap();
	Ok(lock.clone())
}

#[api(SetNameReq)]
fn set_name(req: SetNameReq, name: &SharedName) -> Result<(), Error> {
	let mut lock = name.0.lock().unwrap();
	*lock = req.name;

	Ok(())
}

#[tokio::main]
async fn main() {
	let name = SharedName(Mutex::new(Name {
		firstname: "Albert".into(),
		lastname: "Einstein".into()
	}));

	let mut server = fire::build("0.0.0.0:3000").await
		.expect("Failed to parse address");

	server.add_data(name);

	server.add_route(get_name);
	server.add_route(set_name);

	server.ignite().await.unwrap();
}

Dependencies

~7–20MB
~232K SLoC