ip_api4rs/util/urls.rs
1//! A module that helps you building the correct url for a request.
2
3use serde::Deserialize;
4use serde_aux::prelude::serde_introspect;
5
6/// Builds the url for a request.
7/// The fields are automatically extracted from the struct.
8///
9/// # Arguments
10/// * `https` - A `bool` indicating whether the url should be built for a HTTPS request or not.
11/// * `ip` - The IP address to query for.
12///
13/// # Returns
14/// A `String` containing the url for the request.
15pub fn build_url_from_struct<'de, T>(https: bool, ip: &String) -> String
16where
17 T: Deserialize<'de>,
18{
19 let fields = serde_introspect::<T>();
20 build_url_with_fields(https, ip, fields)
21}
22
23/// Builds the HTTP url for a request.
24/// The fields are automatically extracted from the struct.
25///
26/// # Arguments
27/// * `ip` - The IP address to query for.
28///
29/// # Returns
30/// A `String` containing the url for the request.
31pub fn build_http_url_from_struct<'de, T>(ip: &String) -> String
32where
33 T: Deserialize<'de>,
34{
35 let fields = serde_introspect::<T>();
36 build_url_with_fields(false, ip, fields)
37}
38
39/// Builds the HTTPS url for a request.
40/// The fields are automatically extracted from the struct.
41///
42/// # Arguments
43/// * `ip` - The IP address to query for.
44///
45/// # Returns
46/// A `String` containing the url for the request.
47pub fn build_https_url_from_struct<'de, T>(ip: &String) -> String
48where
49 T: Deserialize<'de>,
50{
51 let fields = serde_introspect::<T>();
52 build_url_with_fields(true, ip, fields)
53}
54
55/// Builds the url for a request without fields.
56/// # Arguments
57/// * `https` - A `bool` indicating whether the url should be built for a HTTPS request or not.
58/// * `ip` - The IP address to query for.
59///
60/// # Returns
61/// A `String` containing the url for the request.
62pub fn build_url_without_fields(https: bool, ip: &String) -> String {
63 match https {
64 true => format!("{}{}", crate::constant::HTTPS_HOST, ip),
65 false => format!("{}{}", crate::constant::HTTP_HOST, ip),
66 }
67}
68
69/// Builds the url for a request with fields.
70/// # Arguments
71/// * `https` - A `bool` indicating whether the url should be built for a HTTPS request or not.
72/// * `ip` - The IP address to query for.
73///
74/// # Returns
75/// A `String` containing the url for the request.
76pub fn build_url_with_fields(https: bool, ip: &String, fields: &[&'static str]) -> String {
77 let mut fields_str = fields.join(",");
78 if !fields.contains(&"message") {
79 //We do this to get the error message if an error occurs.
80 fields_str = fields.join(",") + ",message";
81 }
82 match https {
83 true => format!("{}{}?fields={}", crate::constant::HTTPS_HOST, ip, fields_str),
84 false => format!("{}{}?fields={}", crate::constant::HTTP_HOST, ip, fields_str),
85 }
86}