1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
use reqwest::StatusCode;
use serde::{Deserialize, Serialize};
use std::fmt;

pub mod builder {

    use super::*;

    #[derive(Debug, Clone, Default)]
    pub struct MirrorHeadersBuilder<'a> {
        pass_all: bool,
        pass: Vec<&'a str>,
        remove: Vec<&'a str>,
        set: Vec<(&'a str, &'a str)>,
    }

    impl<'a> MirrorHeadersBuilder<'a> {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_pass_all(mut self, value: bool) -> Self {
            self.pass_all = value;
            self
        }

        pub fn with_pass(mut self, value: Vec<&'a str>) -> Self {
            self.pass = value;
            self
        }

        pub fn with_remove(mut self, value: Vec<&'a str>) -> Self {
            self.remove = value;
            self
        }

        pub fn with_set(mut self, value: Vec<(&'a str, &'a str)>) -> Self {
            self.set = value;
            self
        }

        pub fn build(&self) -> MirrorHeaders {
            MirrorHeaders {
                pass_all: Some(self.pass_all),
                pass: if self.pass.is_empty() {
                    None
                } else {
                    Some(self.pass.iter().map(|value| value.to_string()).collect())
                },
                remove: if self.remove.is_empty() {
                    None
                } else {
                    Some(self.remove.iter().map(|value| value.to_string()).collect())
                },
                set: if self.set.is_empty() {
                    None
                } else {
                    Some({
                        self.set
                            .iter()
                            .map(|item| Set {
                                key: item.0.to_string(),
                                value: item.1.to_string(),
                            })
                            .collect()
                    })
                },
            }
        }
    }

    #[derive(Debug, Default, Clone)]
    pub struct RedirectBuilder<'a> {
        redirect_type: RedirectType,
        protocol: Option<&'a str>,
        pass_query_string: Option<&'a str>,
        replace_key_with: Option<&'a str>,
        mirror_url: Option<&'a str>,
        mirror_pass_query_string: Option<bool>,
        mirror_follow_redirect: Option<bool>,
        mirror_check_md5: Option<bool>,
        mirror_headers: Option<MirrorHeaders>,
        enable_replace_prefix: Option<bool>,
        mirror_replace_prefix: Option<bool>,
        http_replace_code: Option<u16>,
        replace_key_prefix_with: Option<&'a str>,
        host_name: Option<&'a str>,
    }

    impl<'a> RedirectBuilder<'a> {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_redirect_type(mut self, value: RedirectType) -> Self {
            self.redirect_type = value;
            self
        }

        pub fn with_protocol(mut self, value: &'a str) -> Self {
            self.protocol = Some(value);
            self
        }

        pub fn pass_query_string(mut self, value: &'a str) -> Self {
            self.pass_query_string = Some(value);
            self
        }

        pub fn with_replace_key_with(mut self, value: &'a str) -> Self {
            self.replace_key_prefix_with = Some(value);
            self
        }

        pub fn with_mirror_url(mut self, value: &'a str) -> Self {
            self.mirror_url = Some(value);
            self
        }

        pub fn with_mirror_pass_query_string(mut self, value: bool) -> Self {
            self.mirror_pass_query_string = Some(value);
            self
        }

        pub fn with_mirror_follow_redirect(mut self, value: bool) -> Self {
            self.mirror_follow_redirect = Some(value);
            self
        }
        pub fn with_mirror_check_md5(mut self, value: bool) -> Self {
            self.mirror_check_md5 = Some(value);
            self
        }

        pub fn with_mirror_headers(mut self, value: MirrorHeaders) -> Self {
            self.mirror_headers = Some(value);
            self
        }

        pub fn with_mirror_replace_prefix(mut self, value: bool) -> Self {
            self.mirror_replace_prefix = Some(value);
            self
        }

        pub fn with_http_replace_code(mut self, value: u16) -> Self {
            self.http_replace_code = Some(value);
            self
        }

        pub fn with_replace_key_prefix_with(mut self, value: &'a str) -> Self {
            self.replace_key_prefix_with = Some(value);
            self
        }

        pub fn with_host_name(mut self, value: &'a str) -> Self {
            self.host_name = Some(value);
            self
        }

        pub fn build(&self) -> Redirect {
            Redirect {
                redirect_type: self.redirect_type.clone(),
                protocol: self.protocol.map(|e| e.to_string()),
                pass_query_string: self.pass_query_string.map(|e| e.to_string()),
                replace_key_with: self.replace_key_with.map(|e| e.to_string()),
                mirror_url: self.mirror_url.map(|e| e.to_string()),
                mirror_pass_query_string: self.mirror_pass_query_string,
                mirror_follow_redirect: self.mirror_follow_redirect,
                mirror_check_md5: self.mirror_check_md5,
                mirror_headers: self.mirror_headers.clone(),
                enable_replace_prefix: self.enable_replace_prefix,
                http_redirect_code: self.http_replace_code,
                replace_key_prefix_with: self.replace_key_prefix_with.map(|e| e.to_string()),
                host_name: self.host_name.map(|e| e.to_string()),
            }
        }
    }

    #[derive(Debug, Default)]
    pub struct ConditionBuilder<'a> {
        pub key_prefix_equals: Option<&'a str>,
        pub http_error_code_returned_equals: Option<u16>,
        pub key_suffix_equals: Option<&'a str>,
        pub include_header_key: Option<&'a str>,
        pub include_header_equals: Option<&'a str>,
    }

    impl<'a> ConditionBuilder<'a> {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_key_prefix_equals(mut self, value: &'a str) -> Self {
            self.key_prefix_equals = Some(value);
            self
        }

        pub fn with_http_error_code_returned_equals(mut self, value: u16) -> Self {
            self.http_error_code_returned_equals = Some(value);
            self
        }

        pub fn with_key_suffix_equals(mut self, value: &'a str) -> Self {
            self.key_suffix_equals = Some(value);
            self
        }

        pub fn with_include_header_key(mut self, value: &'a str) -> Self {
            self.include_header_key = Some(value);
            self
        }

        pub fn with_include_header_equals(mut self, value: &'a str) -> Self {
            self.include_header_equals = Some(value);
            self
        }

        pub fn build(&self) -> Condition {
            Condition {
                include_header: if let Some(include_header_key) = self.include_header_key {
                    Some(IncludeHeader {
                        key: include_header_key.to_string(),
                        equals: self.include_header_equals.map(|e| e.to_string()),
                    })
                } else {
                    None
                },
                key_prefix_equals: self.key_prefix_equals.map(|e| e.to_string()),
                http_error_code_returned_equals: self.http_error_code_returned_equals,
                key_suffix_equals: self.key_suffix_equals.map(|e| e.to_string()),
            }
        }
    }

    #[derive(Debug, Default)]
    pub struct IndexDocumentBuilder<'a> {
        suffix: &'a str,
        support_sub_dir: bool,
        r#type: u16,
    }

    impl<'a> IndexDocumentBuilder<'a> {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_suffix(mut self, value: &'a str) -> Self {
            self.suffix = value;
            self
        }

        pub fn with_support_sub_dir(mut self, value: bool) -> Self {
            self.support_sub_dir = value;
            self
        }

        pub fn with_type(mut self, value: u16) -> Self {
            self.r#type = value;
            self
        }

        pub fn build(&self) -> IndexDocument {
            IndexDocument {
                suffix: self.suffix.to_string(),
                support_sub_dir: Some(self.support_sub_dir),
                r#type: Some(self.r#type),
            }
        }
    }

    #[derive(Debug, Default)]
    pub struct ErrorDocumentBuilder<'a> {
        key: &'a str,
        http_status: StatusCode,
    }

    impl<'a> ErrorDocumentBuilder<'a> {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_key(mut self, value: &'a str) -> Self {
            self.key = value;
            self
        }

        pub fn with_http_status(mut self, value: StatusCode) -> Self {
            self.http_status = value;
            self
        }

        pub fn build(&self) -> ErrorDocument {
            ErrorDocument {
                key: self.key.to_string(),
                http_status: Some(self.http_status.as_u16()),
            }
        }
    }

    #[derive(Debug, Default, Clone)]
    pub struct RoutingRuleBuilder {
        rule: RoutingRule,
    }

    impl RoutingRuleBuilder {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_rule_number(mut self, value: u32) -> Self {
            self.rule.rule_number = value;
            self
        }

        pub fn with_condition(mut self, value: Condition) -> Self {
            self.rule.condition = value;
            self
        }
        pub fn with_redirect(mut self, value: Redirect) -> Self {
            self.rule.redirect = value;
            self
        }

        pub fn build(&self) -> RoutingRule {
            self.rule.clone()
        }
    }

    #[derive(Debug, Default, Clone)]
    pub struct RoutingRulesBuilder {
        rules: Vec<RoutingRule>,
    }

    impl RoutingRulesBuilder {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_rule(mut self, value: RoutingRule) -> Self {
            self.rules.push(value);
            self
        }

        pub fn build(&self) -> RoutingRules {
            RoutingRules {
                routing_rule: if self.rules.is_empty() {
                    None
                } else {
                    Some(self.rules.clone())
                },
            }
        }
    }

    #[derive(Debug, Default)]
    pub struct WebsiteConfigurationBuilder {
        pub index_document: Option<IndexDocument>,
        pub error_document: Option<ErrorDocument>,
        pub routing_rules: Option<RoutingRules>,
    }

    impl WebsiteConfigurationBuilder {
        pub fn new() -> Self {
            Self::default()
        }

        pub fn with_index_document(mut self, value: IndexDocument) -> Self {
            self.index_document = Some(value);
            self
        }
        pub fn with_error_document(mut self, value: ErrorDocument) -> Self {
            self.error_document = Some(value);
            self
        }

        pub fn with_routing_rules(mut self, value: RoutingRules) -> Self {
            self.routing_rules = Some(value);
            self
        }

        pub fn build(&self) -> WebsiteConfiguration {
            WebsiteConfiguration {
                index_document: self.index_document.clone(),
                error_document: self.error_document.clone(),
                routing_rules: self.routing_rules.clone(),
            }
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub enum RedirectType {
    #[default]
    /// 镜像回源
    Mirror,
    /// 外部跳转,即OSS会返回一个3xx请求,指定跳转到另外一个地址
    External,
    /// 阿里云CDN跳转,主要用于阿里云的CDN。与External不同的是,OSS会额外添加
    /// 一个Header。 阿里云CDN识别到此Header后会主动跳转到指定的地址,返回给用
    /// 户获取到的数据,而不是将3xx跳转请求返回给用户
    AliCDN,
}

impl fmt::Display for RedirectType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Self::Mirror => "Mirror",
                Self::External => "External",
                Self::AliCDN => "AliCDN",
            }
        )
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Set {
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "Value")]
    pub value: String,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct MirrorHeaders {
    #[serde(rename = "PassAll", skip_serializing_if = "Option::is_none")]
    pub pass_all: Option<bool>,
    #[serde(rename = "Pass", skip_serializing_if = "Option::is_none")]
    pub pass: Option<Vec<String>>,
    #[serde(rename = "Remove", skip_serializing_if = "Option::is_none")]
    pub remove: Option<Vec<String>>,
    #[serde(rename = "Set", skip_serializing_if = "Option::is_none")]
    pub set: Option<Vec<Set>>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Redirect {
    #[serde(rename = "RedirectType")]
    pub redirect_type: RedirectType,
    #[serde(rename = "Protocol", skip_serializing_if = "Option::is_none")]
    pub protocol: Option<String>,
    #[serde(rename = "PassQueryString", skip_serializing_if = "Option::is_none")]
    pub pass_query_string: Option<String>,
    #[serde(rename = "ReplaceKeyWith", skip_serializing_if = "Option::is_none")]
    pub replace_key_with: Option<String>,
    #[serde(rename = "MirrorURL", skip_serializing_if = "Option::is_none")]
    pub mirror_url: Option<String>,
    #[serde(
        rename = "MirrorPassQueryString",
        skip_serializing_if = "Option::is_none"
    )]
    pub mirror_pass_query_string: Option<bool>,
    #[serde(
        rename = "MirrorFollowRedirect",
        skip_serializing_if = "Option::is_none"
    )]
    pub mirror_follow_redirect: Option<bool>,
    #[serde(rename = "MirrorCheckMd5", skip_serializing_if = "Option::is_none")]
    pub mirror_check_md5: Option<bool>,
    #[serde(rename = "MirrorHeaders", skip_serializing_if = "Option::is_none")]
    pub mirror_headers: Option<MirrorHeaders>,
    #[serde(
        rename = "EnableReplacePrefix",
        skip_serializing_if = "Option::is_none"
    )]
    pub enable_replace_prefix: Option<bool>,
    #[serde(rename = "HttpRedirectCode", skip_serializing_if = "Option::is_none")]
    pub http_redirect_code: Option<u16>,
    #[serde(
        rename = "ReplaceKeyPrefixWith",
        skip_serializing_if = "Option::is_none"
    )]
    pub replace_key_prefix_with: Option<String>,
    #[serde(rename = "HostName", skip_serializing_if = "Option::is_none")]
    pub host_name: Option<String>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct IncludeHeader {
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "Equals", skip_serializing_if = "Option::is_none")]
    pub equals: Option<String>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct Condition {
    #[serde(rename = "KeyPrefixEquals", skip_serializing_if = "Option::is_none")]
    pub key_prefix_equals: Option<String>,
    #[serde(
        rename = "HttpErrorCodeReturnedEquals",
        skip_serializing_if = "Option::is_none"
    )]
    pub http_error_code_returned_equals: Option<u16>,
    #[serde(rename = "IncludeHeader", skip_serializing_if = "Option::is_none")]
    pub include_header: Option<IncludeHeader>,
    #[serde(rename = "KeySuffixEquals", skip_serializing_if = "Option::is_none")]
    pub key_suffix_equals: Option<String>,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RoutingRule {
    #[serde(rename = "RuleNumber")]
    pub rule_number: u32,
    #[serde(rename = "Condition")]
    pub condition: Condition,
    #[serde(rename = "Redirect")]
    pub redirect: Redirect,
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct RoutingRules {
    #[serde(rename = "RoutingRule", skip_serializing_if = "Option::is_none")]
    pub routing_rule: Option<Vec<RoutingRule>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// 默认主页的容器
pub struct IndexDocument {
    #[serde(rename = "Suffix")]
    /// 设置默认主页后,如果访问以正斜线(/)结尾的Object,则OSS都会返回此默认主页。
    pub suffix: String,
    #[serde(rename = "SupportSubDir", skip_serializing_if = "Option::is_none")]
    /// 访问子目录时,是否支持跳转到子目录下的默认主页。取值范围如下:
    pub support_sub_dir: Option<bool>,
    #[serde(rename = "Type", skip_serializing_if = "Option::is_none")]
    /// 设置默认主页后,访问以非正斜线(/)结尾的Object,且该Object不存在时的行为。
    pub r#type: Option<u16>,
}

impl Default for IndexDocument {
    fn default() -> Self {
        Self {
            suffix: "index.html".to_string(),
            support_sub_dir: Some(true),
            r#type: Some(0),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ErrorDocument {
    #[serde(rename = "Key")]
    pub key: String,
    #[serde(rename = "HttpStatus", skip_serializing_if = "Option::is_none")]
    pub http_status: Option<u16>,
}

impl Default for ErrorDocument {
    fn default() -> Self {
        Self {
            key: "error.html".to_string(),
            http_status: Some(StatusCode::NOT_FOUND.as_u16()),
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct WebsiteConfiguration {
    // 默认主页的容器
    #[serde(rename = "IndexDocument", skip_serializing_if = "Option::is_none")]
    pub index_document: Option<IndexDocument>,
    #[serde(rename = "ErrorDocument", skip_serializing_if = "Option::is_none")]
    pub error_document: Option<ErrorDocument>,
    #[serde(rename = "RoutingRules", skip_serializing_if = "Option::is_none")]
    pub routing_rules: Option<RoutingRules>,
}

#[cfg(test)]
pub mod tests {
    use reqwest::StatusCode;

    use super::{
        builder::{
            ConditionBuilder, ErrorDocumentBuilder, IndexDocumentBuilder, MirrorHeadersBuilder,
            RedirectBuilder, RoutingRulesBuilder, WebsiteConfigurationBuilder,
        },
        RedirectType,
    };
    use crate::oss::entities::website::{RoutingRule, Set, WebsiteConfiguration};

    #[test]
    fn website_configuration_parse_1() {
        let xml_content = r#"<WebsiteConfiguration>
<IndexDocument>
    <Suffix>index.html</Suffix>
    <SupportSubDir>true</SupportSubDir>
    <Type>0</Type>
</IndexDocument>
<ErrorDocument>
    <Key>error.html</Key>
    <HttpStatus>404</HttpStatus>
</ErrorDocument>
<RoutingRules>
    <RoutingRule>
    <RuleNumber>1</RuleNumber>
    <Condition>
        <KeyPrefixEquals>abc/</KeyPrefixEquals>
        <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <Redirect>
        <RedirectType>Mirror</RedirectType>
        <PassQueryString>true</PassQueryString>
        <MirrorURL>http://example.com/</MirrorURL>   
        <MirrorPassQueryString>true</MirrorPassQueryString>
        <MirrorFollowRedirect>true</MirrorFollowRedirect>
        <MirrorCheckMd5>false</MirrorCheckMd5>
        <MirrorHeaders>
        <PassAll>true</PassAll>
        <Pass>myheader-key1</Pass>
        <Pass>myheader-key2</Pass>
        <Remove>myheader-key3</Remove>
        <Remove>myheader-key4</Remove>
        <Set>
            <Key>myheader-key5</Key>
            <Value>myheader-value5</Value>
        </Set>
        </MirrorHeaders>
    </Redirect>
    </RoutingRule>
    <RoutingRule>
    <RuleNumber>2</RuleNumber>
    <Condition>
        <KeyPrefixEquals>abc/</KeyPrefixEquals>
        <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
        <IncludeHeader>
        <Key>host</Key>
        <Equals>test.oss-cn-beijing-internal.aliyuncs.com</Equals>
        </IncludeHeader>
    </Condition>
    <Redirect>
        <RedirectType>AliCDN</RedirectType>
        <Protocol>http</Protocol>
        <HostName>example.com</HostName>
        <PassQueryString>false</PassQueryString>
        <ReplaceKeyWith>prefix/${key}.suffix</ReplaceKeyWith>
        <HttpRedirectCode>301</HttpRedirectCode>
    </Redirect>
    </RoutingRule>
    <RoutingRule>
    <Condition>
        <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
    </Condition>
    <RuleNumber>3</RuleNumber>
    <Redirect>
        <ReplaceKeyWith>prefix/${key}</ReplaceKeyWith>
        <HttpRedirectCode>302</HttpRedirectCode>
        <EnableReplacePrefix>false</EnableReplacePrefix>
        <PassQueryString>false</PassQueryString>
        <Protocol>http</Protocol>
        <HostName>example.com</HostName>
        <RedirectType>External</RedirectType>
    </Redirect>
    </RoutingRule>
</RoutingRules>
</WebsiteConfiguration>
"#;

        let object: WebsiteConfiguration = quick_xml::de::from_str(xml_content).unwrap();
        let left = "index.html";
        let right = object.index_document.unwrap().suffix;
        assert_eq!(left, right)
    }

    #[test]
    fn website_configuration_parse_2() {
        let xml_content = r#"<?xml version="1.0" encoding="UTF-8"?>
<WebsiteConfiguration>
  <IndexDocument>
    <Suffix>index.html</Suffix>
  </IndexDocument>
  <ErrorDocument>
    <Key>error.html</Key>
    <HttpStatus>404</HttpStatus>
  </ErrorDocument>
  <RoutingRules>
    <RoutingRule>
      <RuleNumber>1</RuleNumber>
      <Condition>
        <KeyPrefixEquals>abc/</KeyPrefixEquals>
        <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
      </Condition>
      <Redirect>
        <RedirectType>Mirror</RedirectType>
        <PassQueryString>true</PassQueryString>
        <MirrorURL>http://example.com/</MirrorURL>  
        <MirrorPassQueryString>true</MirrorPassQueryString>
        <MirrorFollowRedirect>true</MirrorFollowRedirect>
        <MirrorCheckMd5>false</MirrorCheckMd5>
        <MirrorHeaders>
          <PassAll>true</PassAll>
          <Pass>myheader-key1</Pass>
          <Pass>myheader-key2</Pass>
          <Remove>myheader-key3</Remove>
          <Remove>myheader-key4</Remove>
          <Set>
            <Key>myheader-key5</Key>
            <Value>myheader-value5</Value>
          </Set>
        </MirrorHeaders>
      </Redirect>
    </RoutingRule>
    <RoutingRule>
      <RuleNumber>2</RuleNumber>
      <Condition>
        <IncludeHeader>
          <Key>host</Key>
          <Equals>test.oss-cn-beijing-internal.aliyuncs.com</Equals>
        </IncludeHeader>
        <KeyPrefixEquals>abc/</KeyPrefixEquals>
        <HttpErrorCodeReturnedEquals>404</HttpErrorCodeReturnedEquals>
      </Condition>
      <Redirect>
        <RedirectType>AliCDN</RedirectType>
        <Protocol>http</Protocol>
        <HostName>example.com</HostName>
        <PassQueryString>false</PassQueryString>
        <ReplaceKeyWith>prefix/${key}.suffix</ReplaceKeyWith>
        <HttpRedirectCode>301</HttpRedirectCode>
      </Redirect>
    </RoutingRule>
  </RoutingRules>
</WebsiteConfiguration>"#;

        let object: WebsiteConfiguration = quick_xml::de::from_str(xml_content).unwrap();
        let left = "index.html";
        let right = object.index_document.unwrap().suffix;
        assert_eq!(left, right)
    }

    #[test]
    fn mirror_headers_builder() {
        let obj = MirrorHeadersBuilder::new()
            .with_pass(["pass1", "pass2"].to_vec())
            .with_remove(["remove1", "remove2"].to_vec())
            .with_pass_all(true)
            .with_set([("lable", "value"), ("label1", "value1")].to_vec())
            .build();
        let left = Set {
            key: "label1".to_string(),
            value: "value1".to_string(),
        };
        let right = &obj.set.unwrap()[1];
        assert_eq!(left.key, right.key);
    }

    #[test]
    fn redirect_builder() {
        let redirect = RedirectBuilder::new()
            .with_host_name("xuetube.com")
            .with_http_replace_code(302)
            .with_mirror_check_md5(true)
            .with_mirror_follow_redirect(false)
            .with_mirror_headers(
                MirrorHeadersBuilder::new()
                    .with_pass(["pass1", "pass2"].to_vec())
                    .with_remove(["remove1", "remove2"].to_vec())
                    .with_pass_all(true)
                    .with_set([("name", "sjy"), ("age", "18")].to_vec())
                    .build(),
            )
            .with_mirror_pass_query_string(false)
            .with_mirror_replace_prefix(false)
            .with_mirror_url("http://example.com")
            .with_protocol("https")
            .with_redirect_type(RedirectType::AliCDN)
            .with_replace_key_with("test")
            .build();
        let left = "pass1";
        let right = &redirect.mirror_headers.unwrap().pass.unwrap()[0];
        assert_eq!(left, right);
    }

    #[test]
    fn condition_builder() {
        let condition = ConditionBuilder::new()
            .with_include_header_key("key")
            .with_include_header_equals("test")
            .with_http_error_code_returned_equals(203)
            .with_key_prefix_equals("prefix")
            .with_key_suffix_equals("suffix")
            .build();
        let left = "key";
        let right = condition.include_header.unwrap().key;
        assert_eq!(left, right);
    }

    #[test]
    fn web_config_builder() {
        let config = WebsiteConfigurationBuilder::new()
            .with_index_document(
                IndexDocumentBuilder::new()
                    .with_suffix("test")
                    .with_support_sub_dir(true)
                    .with_type(200)
                    .build(),
            )
            .with_error_document(
                ErrorDocumentBuilder::new()
                    .with_http_status(StatusCode::NOT_FOUND)
                    .with_key("abcd")
                    .build(),
            )
            .with_routing_rules(
                RoutingRulesBuilder::new()
                    .with_rule(RoutingRule {
                        rule_number: 100,
                        condition: ConditionBuilder::new().build(),
                        redirect: RedirectBuilder::new().build(),
                    })
                    .build(),
            )
            .build();
        let left = r#"<WebsiteConfiguration><IndexDocument><Suffix>test</Suffix><SupportSubDir>true</SupportSubDir><Type>200</Type></IndexDocument><ErrorDocument><Key>abcd</Key><HttpStatus>404</HttpStatus></ErrorDocument><RoutingRules><RoutingRule><RuleNumber>100</RuleNumber><Condition/><Redirect><RedirectType>Mirror</RedirectType></Redirect></RoutingRule></RoutingRules></WebsiteConfiguration>"#;
        let right = quick_xml::se::to_string(&config).unwrap();
        assert_eq!(left, right);
    }
}