extension_api 0.0.8

自定义wasm plugin 扩展api
Documentation
use crate::wit::workoss::extension::extension_http::{
    HttpMethod, HttpRequest, HttpResponse, HttpResponseStream, RedirectPolicy, fetch, fetch_stream,
};

/// HttpRequest::builder()
/// .url()
/// .method()
/// .header("x-myheader","")
/// .body
/// .build()

impl HttpRequest {
    // httprequest builder
    pub fn builder() -> HttpRequestBuilder {
        HttpRequestBuilder::new()
    }
    // executes http
    pub fn fetch(&self) -> Result<HttpResponse, String> {
        fetch(self)
    }
    // execute http stream
    pub fn fetch_stream(&self) -> Result<HttpResponseStream, String> {
        fetch_stream(self)
    }
}

#[derive(Clone)]
pub struct HttpRequestBuilder {
    method: Option<HttpMethod>,
    url: Option<String>,
    headers: Vec<(String, String)>,
    body: Option<Vec<u8>>,
    redirect_policy: RedirectPolicy,
}

impl HttpRequestBuilder {
    /// new HttpRequestBuilder
    pub fn new() -> Self {
        HttpRequestBuilder {
            method: None,
            url: None,
            headers: Vec::new(),
            body: None,
            redirect_policy: RedirectPolicy::NoFollow,
        }
    }
    /// Sets the method for the request.
    pub fn method(mut self, method: HttpMethod) -> Self {
        self.method = Some(method);
        self
    }
    /// Sets the URL for the request.
    pub fn url(mut self, url: impl Into<String>) -> Self {
        self.url = Some(url.into());
        self
    }
    /// add the header for the request.
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }
    /// extend headers
    pub fn headers(mut self, headers: impl IntoIterator<Item = (String, String)>) -> Self {
        self.headers.extend(headers);
        self
    }
    /// set body
    pub fn body(mut self, body: impl Into<Vec<u8>>) -> Self {
        self.body = Some(body.into());
        self
    }
    /// Sets the redirect policy for the request.
    pub fn redirect_policy(mut self, policy: RedirectPolicy) -> Self {
        self.redirect_policy = policy;
        self
    }

    pub fn build(self) -> Result<HttpRequest, String> {
        let method = self.method.unwrap_or(HttpMethod::Get);
        let url = self.url.ok_or_else(|| "URL not set".to_string())?;

        Ok(HttpRequest {
            method,
            url,
            headers: self.headers,
            body: self.body,
            redirect_policy: self.redirect_policy,
        })
    }
}

impl Default for HttpRequestBuilder {
    fn default() -> Self {
        Self::new()
    }
}