Skip to main content

rivet_http/
lib.rs

1use std::collections::HashMap;
2
3pub type Headers = HashMap<String, String>;
4pub type QueryParams = Vec<(String, String)>;
5
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub enum Method {
8    Get,
9    Post,
10    Put,
11    Patch,
12    Delete,
13    Head,
14    Options,
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct Request {
19    pub method: Method,
20    pub path: String,
21    pub headers: Headers,
22    pub query: QueryParams,
23    pub body: Vec<u8>,
24}
25
26impl Request {
27    pub fn new(method: Method, path: impl Into<String>) -> Self {
28        Self {
29            method,
30            path: path.into(),
31            headers: Headers::new(),
32            query: Vec::new(),
33            body: Vec::new(),
34        }
35    }
36}
37
38#[derive(Debug, Clone, PartialEq, Eq)]
39pub struct Response {
40    pub status: u16,
41    pub headers: Headers,
42    pub body: Vec<u8>,
43}
44
45impl Response {
46    pub fn new(status: u16) -> Self {
47        Self {
48            status,
49            headers: Headers::new(),
50            body: Vec::new(),
51        }
52    }
53
54    pub fn ok(body: impl Into<Vec<u8>>) -> Self {
55        let mut res = Self::new(200);
56        res.body = body.into();
57        res
58    }
59
60    pub fn not_found() -> Self {
61        Self::new(404)
62    }
63
64    pub fn method_not_allowed(allow: &[Method]) -> Self {
65        let mut res = Self::new(405);
66        let allow_value = allow
67            .iter()
68            .map(|m| match m {
69                Method::Get => "GET",
70                Method::Post => "POST",
71                Method::Put => "PUT",
72                Method::Patch => "PATCH",
73                Method::Delete => "DELETE",
74                Method::Head => "HEAD",
75                Method::Options => "OPTIONS",
76            })
77            .collect::<Vec<_>>()
78            .join(", ");
79
80        res.headers.insert("allow".to_string(), allow_value);
81        res
82    }
83
84    pub fn not_implemented() -> Self {
85        Self::new(501)
86    }
87
88    pub fn internal_error() -> Self {
89        Self::new(500)
90    }
91}