Skip to main content

faker_rust/default/
internet_http.rs

1//! Internet HTTP generator
2
3use crate::base::sample;
4use crate::locale::fetch_locale;
5
6/// Generate a random HTTP method
7pub fn method() -> String {
8    fetch_locale("internet_http.methods", "en")
9        .map(|v| sample(&v))
10        .unwrap_or_else(|| sample(FALLBACK_METHODS).to_string())
11}
12
13/// Generate a random HTTP status code
14pub fn status_code() -> String {
15    fetch_locale("internet_http.status_codes", "en")
16        .map(|v| sample(&v))
17        .unwrap_or_else(|| sample(FALLBACK_STATUS_CODES).to_string())
18}
19
20/// Generate a random HTTP header
21pub fn header() -> String {
22    fetch_locale("internet_http.headers", "en")
23        .map(|v| sample(&v))
24        .unwrap_or_else(|| sample(FALLBACK_HEADERS).to_string())
25}
26
27/// Generate a random HTTP content type
28pub fn content_type() -> String {
29    fetch_locale("internet_http.content_types", "en")
30        .map(|v| sample(&v))
31        .unwrap_or_else(|| sample(FALLBACK_CONTENT_TYPES).to_string())
32}
33
34// Fallback data
35const FALLBACK_METHODS: &[&str] = &[
36    "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", "CONNECT", "TRACE",
37];
38
39const FALLBACK_STATUS_CODES: &[&str] = &[
40    "200", "201", "204", "301", "302", "304", "400", "401", "403", "404",
41    "405", "500", "502", "503", "504",
42];
43
44const FALLBACK_HEADERS: &[&str] = &[
45    "Accept", "Accept-Charset", "Accept-Encoding", "Accept-Language",
46    "Authorization", "Cache-Control", "Connection", "Content-Length",
47    "Content-Type", "Cookie", "Date", "Host", "If-Match", "If-Modified-Since",
48    "If-None-Match", "Origin", "Referer", "User-Agent",
49];
50
51const FALLBACK_CONTENT_TYPES: &[&str] = &[
52    "application/json", "application/xml", "text/html", "text/plain",
53    "text/css", "text/javascript", "application/pdf", "image/jpeg",
54    "image/png", "image/gif", "application/octet-stream",
55];
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_method() {
63        assert!(!method().is_empty());
64    }
65
66    #[test]
67    fn test_status_code() {
68        assert!(!status_code().is_empty());
69    }
70
71    #[test]
72    fn test_header() {
73        assert!(!header().is_empty());
74    }
75
76    #[test]
77    fn test_content_type() {
78        assert!(!content_type().is_empty());
79    }
80}