Function fetch_shortcode

Source
pub fn fetch_shortcode(
    url: &str,
    method: Option<&str>,
    json_body: Option<&str>,
) -> String
Expand description

Sends an HTTP request to the provided URL using either the GET or POST method and returns the response as a String. This function handles asynchronous requests but executes them in a synchronous context using Tokio function block_in_place. Note: This function is slow. For better performance, consider using the fetch_shortcode_js function instead.

§Parameters

  • url: A string slice that holds the URL to which the HTTP request will be sent.
  • method: An optional HTTP method, either GET or POST. Defaults to GET if None is provided.
  • json_body: An optional JSON string to be used as the request body for POST requests. Defaults to an empty JSON object ({}) if None is provided. This parameter is ignored for GET requests.

§Returns

A String containing either the response body from the server or an error message in case of failure.

  • If the HTTP request succeeds and returns a valid response, the body of the response is returned as a String.
  • If the HTTP request fails (due to network errors, invalid URLs, or server errors), a descriptive error message is returned.

§Error Handling

  • If an invalid HTTP method is provided, the function returns "Invalid method: <method>".
  • If the request fails, either due to network issues or an unsuccessful HTTP status, the function returns an error message like "Request failed with status: <status>" or "Request error: <error>".

§Blocking and Asynchronous Execution

This function uses tokio::task::block_in_place to run the asynchronous request synchronously. This allows the function to be used in synchronous contexts while still performing asynchronous operations under the hood.

§Example

use tera_shortcodes::fetch_shortcode;
 
#[tokio::main]
async fn main() {
    let response = fetch_shortcode(
        "https://example.com/api", 
        Some("POST"), 
        Some(r#"{"key": "value"}"#)
    );

    println!("Response: {}", response);
}

This will perform a POST request to https://example.com/api with the given JSON body and print the response.