Struct aliyun_oss_client::client::Client

source ·
#[non_exhaustive]
pub struct Client<M = ClientWithMiddleware> { /* private fields */ }
Expand description

§构造请求的客户端结构体

Implementations§

source§

impl Client

source

pub async fn get_bucket_list(self) -> Result<ListBuckets, ExtractListError>

从 OSS 获取 bucket 列表

source

pub async fn base_bucket_list<List, Item, E, ItemErr>( &self, list: &mut List ) -> Result<(), ExtractListError>
where List: RefineBucketList<Item, E, ItemErr> + InitObject<Item>, Item: RefineBucket<ItemErr>, E: ListError, ItemErr: Error + 'static,

从 OSS 获取 bucket 列表,并存入自定义类型中

source

pub async fn get_bucket_info(self) -> Result<Bucket, ExtractItemError>

从 OSS 上获取默认的 bucket 信息

source

pub async fn base_bucket_info<Bucket, E>( &self, bucket: &mut Bucket ) -> Result<(), ExtractItemError>
where Bucket: RefineBucket<E>, E: Error + 'static,

§从 OSS 上获取 bucket 的信息,并存入自定义的类型中

默认获取 Client 中的默认 bucket 信息,如需获取其他 bucket,可调用 set_bucket 更改后调用

也可以调用 set_endpoint 更改可用区

source§

impl Client<ClientWithMiddleware>

source

pub fn get_bucket_list(self) -> Result<ListBuckets<RcPointer>, ExtractListError>

获取 bucket 列表

source

pub fn base_bucket_list<List, Item, E, ItemErr>( &self, list: &mut List ) -> Result<(), ExtractListError>
where List: RefineBucketList<Item, E, ItemErr> + InitObject<Item>, Item: RefineBucket<ItemErr>, E: ListError, ItemErr: Error + 'static,

获取 bucket 列表,可存储为自定义的类型

source

pub fn get_bucket_info(self) -> Result<Bucket<RcPointer>, ExtractItemError>

获取当前的 bucket 的信息

source

pub fn base_bucket_info<Bucket, E>( &self, bucket: &mut Bucket ) -> Result<(), ExtractItemError>
where Bucket: RefineBucket<E>, E: Error + 'static,

获取某一个 bucket 的信息,并存储到自定义的类型

source§

impl<M: Default> Client<M>

source

pub fn new( access_key_id: KeyId, access_key_secret: KeySecret, endpoint: EndPoint, bucket: BucketName ) -> Self

使用基本配置信息初始化 Client

source

pub fn from_config(config: Config) -> Self

使用 Config 中的配置初始化 Client

source

pub fn from_env() -> Result<Self, InvalidConfig>

§通过环境变量初始化 Client

如果在 Aliyun ECS 上,可将环境变量 ALIYUN_OSS_INTERNAL 设置为 true / 1 / yes / Y ,即可使用 internal 网络请求 OSS 接口

示例

use std::env::set_var;
set_var("ALIYUN_KEY_ID", "foo1");
set_var("ALIYUN_KEY_SECRET", "foo2");
set_var("ALIYUN_ENDPOINT", "qingdao");
set_var("ALIYUN_BUCKET", "foo4");

use aliyun_oss_client::builder::ClientWithMiddleware;
let client = Client::<ClientWithMiddleware>::from_env();
assert!(client.is_ok());
source§

impl<M> Client<M>

source

pub fn get_bucket_base(&self) -> BucketBase

返回默认可用区,默认 bucket 的 BucketBase

source

pub fn get_bucket_url(&self) -> Url

获取默认的 bucket 的 url

source

pub fn get_endpoint_url(&self) -> Url

获取默认的可用区的 url

source

pub fn set_bucket(&mut self, bucket: BucketName)

更改默认 bucket

source

pub fn set_endpoint(&mut self, endpoint: EndPoint)

更改默认 endpoint

source

pub fn timeout(&mut self, timeout: Duration)

设置 timeout

source

pub fn get_object_base<P>( &self, path: P ) -> Result<ObjectBase, InvalidObjectPath>

根据默认的 bucket,endpoint 和提供的文件路径,获取 ObjectBase

source§

impl Client

source

pub async fn get_object_list<Q: IntoIterator<Item = (QueryKey, QueryValue)>>( &self, query: Q ) -> Result<ObjectList, ExtractListError>

查询默认 bucket 的文件列表

查询条件参数有多种方式,具体参考 get_object_list 文档

source

pub async fn get_object_list2( &self, query: Query ) -> Result<ObjectList, ExtractListError>

查询默认 bucket 的文件列表

source

pub async fn base_object_list<Q: IntoIterator<Item = (QueryKey, QueryValue)>, List, Item, E: ListError, ItemErr: Error + 'static>( &self, query: Q, list: &mut List ) -> Result<(), ExtractListError>
where List: RefineObjectList<Item, E, ItemErr> + InitObject<Item>, Item: RefineObject<ItemErr>,

§可将 object 列表导出到外部类型(关注便捷性)

从 Client 中的默认 bucket 中获取,如需获取其他 bucket 的,可调用 set_bucket 更改后调用

也可以通过调用 set_endpoint 更改可用区

可以参考下面示例,或者项目中的 examples/custom.rs

§示例
use aliyun_oss_client::{
    decode::{ListError, RefineObject, RefineObjectList},
    object::{ExtractListError, InitObject},
    Client,
};
use dotenv::dotenv;
use thiserror::Error;

#[derive(Debug)]
struct MyFile {
    key: String,
    #[allow(dead_code)]
    other: String,
}
impl RefineObject<MyError> for MyFile {
    fn set_key(&mut self, key: &str) -> Result<(), MyError> {
        self.key = key.to_string();
        Ok(())
    }
}

#[derive(Default, Debug)]
struct MyBucket {
    name: String,
    files: Vec<MyFile>,
}

impl RefineObjectList<MyFile, MyError> for MyBucket {
    fn set_name(&mut self, name: &str) -> Result<(), MyError> {
        self.name = name.to_string();
        Ok(())
    }
    fn set_list(&mut self, list: Vec<MyFile>) -> Result<(), MyError> {
        self.files = list;
        Ok(())
    }
}

#[derive(Debug, Error)]
#[error("my error")]
enum MyError {}

impl ListError for MyError {}

async fn run() -> Result<(), ExtractListError> {
    dotenv().ok();
    use aliyun_oss_client::BucketName;

    let client = Client::from_env().unwrap();

    // 除了设置Default 外,还可以做更多设置
    let mut bucket = MyBucket {
        name: "abc".to_string(),
        files: Vec::with_capacity(20),
    };

    // 利用闭包对 MyFile 做一下初始化设置
    impl InitObject<MyFile> for MyBucket {
        fn init_object(&mut self) -> Option<MyFile> {
            Some(MyFile {
              key: String::default(),
              other: "abc".to_string(),
            })
        }
    }

    client.base_object_list([], &mut bucket).await?;

    println!("bucket: {:?}", bucket);

    Ok(())
}
source

pub async fn base_object_list2<List, Item, E: ListError, ItemErr: Error + 'static>( &self, query: &Query, list: &mut List ) -> Result<(), ExtractListError>
where List: RefineObjectList<Item, E, ItemErr> + InitObject<Item>, Item: RefineObject<ItemErr>,

§可将 object 列表导出到外部类型(关注性能)

从 Client 中的默认 bucket 中获取,如需获取其他 bucket 的,可调用 set_bucket 更改后调用

也可以通过调用 set_endpoint 更改可用区

source

pub async fn get_custom_object<Item, ItemErr>( &self, query: &Query ) -> Result<Objects<Item>, ExtractListError>
where Item: RefineObject<ItemErr>, Objects<Item>: InitObject<Item>, ItemErr: Error + 'static,

§获取包含自定义类型的 object 集合

其包含在 ObjectList 对象中

source§

impl Client<ClientWithMiddleware>

source

pub fn get_object_list<Q: IntoIterator<Item = (QueryKey, QueryValue)>>( self, query: Q ) -> Result<ObjectList<RcPointer>, ExtractListError>

查询默认 bucket 的文件列表

查询条件参数有多种方式,具体参考 get_object_list 文档

source

pub fn base_object_list<Q: IntoIterator<Item = (QueryKey, QueryValue)>, List, Item, F, E: ListError, ItemErr: Error + 'static>( &self, query: Q, list: &mut List, init_object: F ) -> Result<(), ExtractListError>
where List: RefineObjectList<Item, E, ItemErr>, Item: RefineObject<ItemErr>, F: Fn(&mut List) -> Option<Item>,

可将 object 列表导出到外部 struct

Trait Implementations§

source§

impl AlignBuilder for Client<ClientWithMiddleware>

source§

fn builder_with_header<H: IntoIterator<Item = (HeaderName, HeaderValue)>>( &self, method: Method, url: Url, resource: CanonicalizedResource, headers: H ) -> Result<RequestBuilder, BuilderError>

§构造自定义的接口请求方法

比如在上传完文件时,返回自己期望的数据,而不是仅返回 etag 信息

§例子是一个获取 object 元信息的接口
use aliyun_oss_client::{errors::OssError, file::AlignBuilder, Client, Method};
use dotenv::dotenv;

async fn run() -> Result<(), OssError> {
    dotenv().ok();
    let client = Client::from_env().unwrap();

    let (url, resource) = client
        .get_object_base("9AB932LY.jpeg")?
        .get_url_resource([]);

    let headers = vec![(
        "If-Unmodified-Since".parse().unwrap(),
        "Sat, 01 Jan 2022 18:01:01 GMT".parse().unwrap(),
    )];

    let builder = client.builder_with_header(Method::HEAD, url, resource, headers)?;

    let response = builder.send().await?;

    println!("status: {:?}", response.status());

    Ok(())
}
§参数
  • method 接口请求方式
  • url 要请求的接口,包含 query 参数等信息
  • resource 阿里云接口需要提供的统一的信息,CanonicalizedResource 提供了 bucket ,object 等各种生成方式,如果无法满足 还可以自己用 trait 来自定义
§返回值

返回值是一个封装了 reqwest::Builder 构造器,RequestBuilder, 提供两个方法 sendsend_adjust_error

  • send 方法,直接返回 reqwest::Response
  • send_adjust_error 方法,会对 api 返回结果进行处理,如果 HTTP 状态码正常(200>= && <300) 则,返回 Ok, 否则,会对返回的 xml 异常数据进行解析,返回 Err(OssService)
source§

fn builder( &self, method: Method, url: Url, resource: CanonicalizedResource ) -> Result<RequestBuilder, BuilderError>

根据具体的 API 接口参数,返回请求的构建器(不带 headers)
source§

impl AlignBuilder for Client<ClientWithMiddleware>

source§

fn builder_with_header<H: IntoIterator<Item = (HeaderName, HeaderValue)>>( &self, method: Method, url: Url, resource: CanonicalizedResource, headers: H ) -> Result<BlockingRequestBuilder, BuilderError>

§向 OSS 发送请求的封装

参数包含请求的:

返回值是一个 reqwest 的请求创建器 reqwest::blocking::RequestBuilder

返回后,可以再加请求参数,然后可选的进行发起请求

source§

fn builder( &self, method: Method, url: Url, resource: CanonicalizedResource ) -> Result<RequestBuilder, BuilderError>

根据具体的 API 接口参数,返回请求的构建器(不带 headers)
source§

impl<M> AsMut<BucketName> for Client<M>

source§

fn as_mut(&mut self) -> &mut BucketName

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<M> AsMut<Option<Duration>> for Client<M>

source§

fn as_mut(&mut self) -> &mut Option<Duration>

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl<M> AsRef<BucketName> for Client<M>

source§

fn as_ref(&self) -> &BucketName

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<M> AsRef<EndPoint> for Client<M>

source§

fn as_ref(&self) -> &EndPoint

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl<M: Clone> Clone for Client<M>

source§

fn clone(&self) -> Client<M>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<M: Debug> Debug for Client<M>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<M: Default> Default for Client<M>

source§

fn default() -> Client<M>

Returns the “default value” for a type. Read more
source§

impl<'a, M: Default + Clone> From<&'a Client<M>> for QueryAuth<'a>

source§

fn from(client: &'a Client<M>) -> Self

Converts to this type from the input type.
source§

impl From<Client<ClientWithMiddleware>> for Content

source§

fn from(value: Client) -> Self

Converts to this type from the input type.
source§

impl<M> From<Client<M>> for BucketBase

source§

fn from(_: Client<M>) -> Self

Converts to this type from the input type.
source§

impl From<Client> for Content

source§

fn from(value: Client) -> Self

Converts to this type from the input type.
source§

impl<M: PartialEq> PartialEq for Client<M>

source§

fn eq(&self, other: &Client<M>) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<M: Default> STS for Client<M>

source§

fn new_with_sts<ST>( access_key_id: KeyId, access_key_secret: KeySecret, endpoint: EndPoint, bucket: BucketName, security_token: ST ) -> Result<Self, InvalidHeaderValue>

用 STS 配置信息初始化 Client
source§

impl<M: Eq> Eq for Client<M>

source§

impl<M> StructuralPartialEq for Client<M>

Auto Trait Implementations§

§

impl<M> Freeze for Client<M>
where M: Freeze,

§

impl<M> RefUnwindSafe for Client<M>
where M: RefUnwindSafe,

§

impl<M> Send for Client<M>
where M: Send,

§

impl<M> Sync for Client<M>
where M: Sync,

§

impl<M> Unpin for Client<M>
where M: Unpin,

§

impl<M> UnwindSafe for Client<M>
where M: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
source§

impl<P, T> Files<P> for T

source§

const DEFAULT_CONTENT_TYPE: &'static str = super::DEFAULT_CONTENT_TYPE

默认的文件类型 Read more
source§

fn put_file<P: Into<PathBuf> + AsRef<Path>>( &self, file_name: P, path: Path ) -> Result<String, FileError>

上传文件到 OSS Read more
source§

fn put_content<F>( &self, content: Vec<u8>, path: Path, get_content_type: F ) -> Result<String, FileError>
where F: Fn(&Vec<u8>) -> Option<&'static str>,

上传文件内容到 OSS Read more
source§

fn put_content_base( &self, content: Vec<u8>, content_type: &str, path: Path ) -> Result<Response, FileError>

最原始的上传文件的方法
source§

fn get_object<Num, R>(&self, path: Path, range: R) -> Result<Vec<u8>, FileError>

获取文件内容 Read more
source§

fn delete_object(&self, path: Path) -> Result<(), FileError>

删除 OSS 上的文件 Read more
source§

impl<P, T> Files<P> for T
where P: Send + Sync + 'static, T: AlignBuilder + GetStdWithPath<P>,

source§

const DEFAULT_CONTENT_TYPE: &'static str = DEFAULT_CONTENT_TYPE

默认的文件类型 Read more
source§

fn put_file<'life0, 'async_trait, P>( &'life0 self, file_name: P, path: Path ) -> Pin<Box<dyn Future<Output = Result<String, FileError>> + Send + 'async_trait>>
where P: 'async_trait + Into<PathBuf> + AsRef<Path> + Send + Sync, Self: Sync + 'async_trait, 'life0: 'async_trait,

上传文件到 OSS Read more
source§

fn put_content<'life0, 'async_trait, F>( &'life0 self, content: Vec<u8>, path: Path, get_content_type: F ) -> Pin<Box<dyn Future<Output = Result<String, FileError>> + Send + 'async_trait>>
where F: Fn(&Vec<u8>) -> Option<&'static str> + Send + Sync + 'async_trait, Self: Sync + 'async_trait, 'life0: 'async_trait,

上传文件内容到 OSS Read more
source§

fn put_content_base<'life0, 'life1, 'async_trait>( &'life0 self, content: Vec<u8>, content_type: &'life1 str, path: Path ) -> Pin<Box<dyn Future<Output = Result<Response, FileError>> + Send + 'async_trait>>
where Self: Sync + 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

最核心的上传文件到 OSS 的方法
source§

fn get_object<'life0, 'async_trait, Num, R>( &'life0 self, path: Path, range: R ) -> Pin<Box<dyn Future<Output = Result<Vec<u8>, FileError>> + Send + 'async_trait>>
where R: Into<ContentRange<Num>> + Send + Sync + 'async_trait, ContentRange<Num>: Into<HeaderValue>, Num: 'async_trait, Self: Sync + 'async_trait, 'life0: 'async_trait,

获取 OSS 上文件的部分或全部内容 Read more
source§

fn delete_object<'life0, 'async_trait>( &'life0 self, path: Path ) -> Pin<Box<dyn Future<Output = Result<(), FileError>> + Send + 'async_trait>>
where Self: Sync + 'async_trait, 'life0: 'async_trait,

删除 OSS 上的文件 Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more