swan_common/types/
http.rs

1use proc_macro2::Ident;
2use syn::parse::{Parse, ParseStream};
3
4/// HTTP 方法枚举
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum HttpMethod {
7    Get,
8    Post,
9    Put,
10    Delete,
11}
12
13impl HttpMethod {
14    /// 返回HTTP方法的字符串表示
15    pub fn as_str(&self) -> &'static str {
16        match self {
17            HttpMethod::Get => "GET",
18            HttpMethod::Post => "POST",
19            HttpMethod::Put => "PUT",
20            HttpMethod::Delete => "DELETE",
21        }
22    }
23
24    /// 返回用于客户端的方法标识符
25    pub fn client_method(&self) -> Ident {
26        Ident::new(
27            match self {
28                HttpMethod::Get => "get",
29                HttpMethod::Post => "post",
30                HttpMethod::Put => "put",
31                HttpMethod::Delete => "delete",
32            },
33            proc_macro2::Span::call_site(),
34        )
35    }
36}
37
38/// 内容类型枚举
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum ContentType {
41    Json,
42    FormUrlEncoded,
43    FormMultipart,
44}
45
46impl Parse for ContentType {
47    fn parse(input: ParseStream) -> syn::Result<Self> {
48        let ident: Ident = input.parse()?;
49        match ident.to_string().as_str() {
50            "json" => Ok(ContentType::Json),
51            "form_urlencoded" => Ok(ContentType::FormUrlEncoded),
52            "form_multipart" => Ok(ContentType::FormMultipart),
53            _ => Err(syn::Error::new_spanned(
54                ident,
55                "content_type must be one of 'json', 'form_urlencoded', or 'form_multipart'",
56            )),
57        }
58    }
59}
60
61#[cfg(test)]
62mod tests {
63    use super::*;
64
65    #[test]
66    fn test_http_method_as_str() {
67        assert_eq!(HttpMethod::Get.as_str(), "GET");
68        assert_eq!(HttpMethod::Post.as_str(), "POST");
69        assert_eq!(HttpMethod::Put.as_str(), "PUT");
70        assert_eq!(HttpMethod::Delete.as_str(), "DELETE");
71    }
72
73    #[test]
74    fn test_http_method_client_method() {
75        assert_eq!(HttpMethod::Get.client_method().to_string(), "get");
76        assert_eq!(HttpMethod::Post.client_method().to_string(), "post");
77        assert_eq!(HttpMethod::Put.client_method().to_string(), "put");
78        assert_eq!(HttpMethod::Delete.client_method().to_string(), "delete");
79    }
80}