Skip to main content

ling_net/
types.rs

1use std::collections::HashMap;
2
3#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4pub enum HttpMethod { Get, Post, Put, Patch, Delete, Head, Options }
5
6impl HttpMethod {
7    pub fn as_str(self) -> &'static str {
8        match self {
9            Self::Get     => "GET",    Self::Post    => "POST",
10            Self::Put     => "PUT",    Self::Patch   => "PATCH",
11            Self::Delete  => "DELETE", Self::Head    => "HEAD",
12            Self::Options => "OPTIONS",
13        }
14    }
15}
16
17#[derive(Debug, Clone)]
18pub struct Request {
19    pub method:  HttpMethod,
20    pub url:     String,
21    pub headers: HashMap<String, String>,
22    pub body:    Option<Vec<u8>>,
23}
24
25impl Request {
26    pub fn get(url: impl Into<String>) -> Self {
27        Self { method: HttpMethod::Get, url: url.into(), headers: HashMap::new(), body: None }
28    }
29
30    pub fn post(url: impl Into<String>, body: impl Into<Vec<u8>>) -> Self {
31        Self { method: HttpMethod::Post, url: url.into(), headers: HashMap::new(), body: Some(body.into()) }
32    }
33
34    pub fn header(mut self, key: impl Into<String>, val: impl Into<String>) -> Self {
35        self.headers.insert(key.into(), val.into());
36        self
37    }
38}
39
40#[derive(Debug, Clone)]
41pub struct Response {
42    pub status:  u16,
43    pub headers: HashMap<String, String>,
44    pub body:    Vec<u8>,
45}
46
47impl Response {
48    pub fn ok(body: impl Into<Vec<u8>>) -> Self {
49        Self { status: 200, headers: HashMap::new(), body: body.into() }
50    }
51
52    pub fn text(&self) -> &str {
53        std::str::from_utf8(&self.body).unwrap_or("")
54    }
55
56    pub fn is_success(&self) -> bool { self.status >= 200 && self.status < 300 }
57}