aliyun_oss_rs/bucket/
put_bucket_referer.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::{RefererConfiguration, RefererList};
11
12/// Configure bucket hotlink protection (Referer whitelist).
13///
14/// See the [Alibaba Cloud documentation](https://help.aliyun.com/zh/oss/developer-reference/putbucketreferer) for details.
15pub struct PutBucketReferer {
16    req: OssRequest,
17    config: RefererConfiguration,
18}
19
20impl PutBucketReferer {
21    pub(super) fn new(oss: Oss) -> Self {
22        let mut req = OssRequest::new(oss, Method::PUT);
23        req.insert_query("referer", "");
24        PutBucketReferer {
25            req,
26            config: RefererConfiguration {
27                allow_empty_referer: true,
28                referer_list: RefererList::default(),
29            },
30        }
31    }
32
33    /// Set whether empty Referer headers are allowed.
34    pub fn allow_empty_referer(mut self, allow: bool) -> Self {
35        self.config.allow_empty_referer = allow;
36        self
37    }
38
39    /// Replace the referer whitelist.
40    pub fn set_whitelist(mut self, referers: Vec<impl ToString>) -> Self {
41        self.config.referer_list.items = referers.into_iter().map(|s| s.to_string()).collect();
42        self
43    }
44
45    /// Send the request.
46    pub async fn send(mut self) -> Result<(), Error> {
47        let body = serde_xml_rs::to_string(&self.config).map_err(|_| Error::InvalidCharacter)?;
48        self.req.set_body(Full::new(Bytes::from(body)));
49        let response = self.req.send_to_oss()?.await?;
50        match response.status() {
51            code if code.is_success() => Ok(()),
52            _ => Err(normal_error(response).await),
53        }
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn test_referer_serialization() {
63        let config = RefererConfiguration {
64            allow_empty_referer: false,
65            referer_list: RefererList {
66                items: vec!["https://example.com".to_string()],
67            },
68        };
69        let xml = serde_xml_rs::to_string(&config).unwrap();
70        assert!(xml.contains("<RefererConfiguration>"));
71        assert!(xml.contains("<AllowEmptyReferer>false</AllowEmptyReferer>"));
72        assert!(xml.contains("<Referer>https://example.com</Referer>"));
73    }
74}