starlane_resources/
http.rs

1use std::collections::HashMap;
2use crate::data::BinSrc;
3use std::str::FromStr;
4use crate::error::Error;
5use serde::{Serialize,Deserialize};
6use std::convert::{TryInto, TryFrom};
7use std::sync::Arc;
8
9pub type Headers = HashMap<String,String>;
10
11
12#[derive(Debug,Clone,Serialize,Deserialize)]
13pub struct HttpResponse{
14    pub status: usize,
15    pub headers: Headers,
16    pub body: BinSrc
17}
18
19
20impl TryInto<BinSrc> for HttpResponse{
21    type Error = Error;
22
23    fn try_into(self) -> Result<BinSrc, Self::Error> {
24        Ok(BinSrc::Memory(Arc::new(bincode::serialize(&self)?)))
25    }
26}
27
28impl TryFrom<BinSrc> for HttpResponse {
29    type Error = Error;
30
31    fn try_from(bin_src: BinSrc) -> Result<Self, Self::Error> {
32        if let BinSrc::Memory(bin) = bin_src {
33            Ok(bincode::deserialize(bin.as_slice() )?)
34        } else {
35            Err(format!("cannot try_from BinSrc of type: {}", bin_src.to_string()).into() )
36        }
37    }
38}
39
40#[derive(Debug,Clone,Serialize,Deserialize)]
41pub struct HttpRequest{
42   pub path: String,
43   pub method: HttpMethod,
44   pub headers: Headers,
45   pub body: BinSrc
46}
47
48impl TryInto<BinSrc> for HttpRequest {
49    type Error = Error;
50
51    fn try_into(self) -> Result<BinSrc, Self::Error> {
52        Ok(BinSrc::Memory(Arc::new(bincode::serialize(&self)?)))
53    }
54}
55
56impl TryFrom<BinSrc> for HttpRequest {
57    type Error = Error;
58
59    fn try_from(bin_src: BinSrc) -> Result<Self, Self::Error> {
60        if let BinSrc::Memory(bin) = bin_src {
61            Ok(bincode::deserialize(bin.as_slice() )?)
62        } else {
63            Err(format!("cannot try_from BinSrc of type: {}", bin_src.to_string()).into() )
64        }
65    }
66}
67
68#[derive(Debug,Clone,Serialize,Deserialize)]
69pub enum HttpMethod {
70    Get,
71    Put,
72    Post,
73    Delete
74}
75
76
77impl FromStr for HttpMethod {
78    type Err = Error;
79
80    fn from_str(s: &str) -> Result<Self, Self::Err> {
81        match s.to_uppercase().trim() {
82            "GET" => Ok(Self::Get),
83            "PUT" => Ok(Self::Put),
84            "POST" => Ok(Self::Post),
85            "DELETE" => Ok(Self::Delete),
86            &_ => Err(format!("method not recognized: {}", s).into())
87        }
88    }
89}
90
91impl ToString for HttpMethod {
92    fn to_string(&self) -> String {
93        match self {
94            HttpMethod::Get => "Get".to_string(),
95            HttpMethod::Put => "Put".to_string(),
96            HttpMethod::Post => "Post".to_string(),
97            HttpMethod::Delete => "Delete".to_string()
98        }
99    }
100}