aliyun_oss_rs/bucket/
put_bucket_website.rs

1use crate::{
2    Error,
3    error::normal_error,
4    request::{Oss, OssRequest},
5};
6use bytes::Bytes;
7use http::Method;
8use http_body_util::Full;
9
10use super::{ErrorDocument, IndexDocument, WebsiteConfiguration};
11
12/// Configure bucket static website hosting.
13///
14/// See the [Alibaba Cloud documentation](https://help.aliyun.com/zh/oss/developer-reference/putbucketwebsite) for details.
15pub struct PutBucketWebsite {
16    req: OssRequest,
17    config: WebsiteConfiguration,
18}
19
20impl PutBucketWebsite {
21    pub(super) fn new(oss: Oss) -> Self {
22        let mut req = OssRequest::new(oss, Method::PUT);
23        req.insert_query("website", "");
24        PutBucketWebsite {
25            req,
26            config: WebsiteConfiguration::default(),
27        }
28    }
29
30    /// Set the index document suffix (for example, `index.html`).
31    pub fn set_index_document(mut self, suffix: impl ToString) -> Self {
32        self.config.index_document = Some(IndexDocument {
33            suffix: suffix.to_string(),
34        });
35        self
36    }
37
38    /// Set the error document key (for example, `error.html`).
39    pub fn set_error_document(mut self, key: impl ToString) -> Self {
40        self.config.error_document = Some(ErrorDocument {
41            key: key.to_string(),
42        });
43        self
44    }
45
46    /// Replace the raw configuration object.
47    pub fn set_configuration(mut self, config: WebsiteConfiguration) -> Self {
48        self.config = config;
49        self
50    }
51
52    /// Send the request.
53    pub async fn send(mut self) -> Result<(), Error> {
54        let body = serde_xml_rs::to_string(&self.config).map_err(|_| Error::InvalidCharacter)?;
55        self.req.set_body(Full::new(Bytes::from(body)));
56        let response = self.req.send_to_oss()?.await?;
57        match response.status() {
58            code if code.is_success() => Ok(()),
59            _ => Err(normal_error(response).await),
60        }
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn test_website_serialization() {
70        let config = WebsiteConfiguration {
71            index_document: Some(IndexDocument {
72                suffix: "index.html".into(),
73            }),
74            error_document: Some(ErrorDocument {
75                key: "error.html".into(),
76            }),
77            routing_rules: None,
78        };
79        let xml = serde_xml_rs::to_string(&config).unwrap();
80        assert!(xml.contains("<WebsiteConfiguration>"));
81        assert!(xml.contains("<Suffix>index.html</Suffix>"));
82        assert!(xml.contains("<Key>error.html</Key>"));
83    }
84}