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
//! 路由
use crate::tina::data::app_error::AppError;
use crate::tina::data::dynamic_value::DynamicValue;
use crate::tina::data::AppResult;
use crate::tina::log::operation::{BusinessType, OperationLog, OperatorType};
use crate::tina::server::application::Application;
use crate::{app_system_error, tina::data::api_schema::ApiSchema};

use crate::tina::data::throttle::ThrottleConfig;
use crate::tina::server::http::route_ext::RouteConfig;
use crate::tina::util::not_empty::INotEmpty;
use http::Method;
use indexmap::{IndexMap, IndexSet};
use once_cell::sync::Lazy;
use std::fmt::{Debug, Display, Formatter};
use std::sync::{Arc, RwLock};
use std::{any::Any, str::FromStr};
use tracing::Level;
use utoipa::openapi::path::Parameter;
use utoipa::openapi::{request_body::RequestBody, Responses};

/// RouteConfig的唯一Key
#[derive(Clone, Hash, Eq, PartialEq)]
pub struct RouteConfigKey {
    /// Http Method
    pub method: HttpMethod,
    /// 路径
    pub path: String,
}

/// 接口route配置
#[derive(Clone)]
pub struct RouteBaseConfig {
    /// route所在的group
    pub api_group: IndexSet<String>,
    /// 接口路径
    pub path: String,
    /// Http Method
    pub method: HttpMethod,
    /// 接口方法名
    pub handler_name: String,
    /// 请求参数文档
    pub request_parameter: Option<Vec<Parameter>>,
    /// 请求体文档
    pub request_body: Option<RequestBody>,
    /// 返回参数文档
    pub response_body: Option<Responses>,
    /// 接口文档标签
    pub tags: Vec<String>,
    /// 接口文档摘要
    pub summary: String,
    /// 接口文档说明
    pub description: Vec<String>,
    /// 是否显示接口文档
    pub show_doc: bool,
    /// 接口文档顺序
    pub order: Option<i32>,
    /// 接口作者
    pub author: Vec<String>,
    /// 检验组
    pub validate_group: Option<Vec<&'static str>>,
    /// 接口文档是否显示Security相关参数
    pub show_security: bool,
    /// 接口是否应用默认的接口路径前缀
    pub enable_default_prefix: bool,
    /// 接口是否开启Security Token
    pub enable_token: bool,
    /// 是否启用自动事务管理(POST、PUT、PATCH、DELETE接口自动附加事务)
    pub enable_auto_transaction: bool,
    /// 接口是否开启参数日志, POST、PUT、DELETE接口默认开启, 其他接口默认不开启
    pub enable_log_param: Option<bool>,
    /// 接口参数日志级别
    pub log_param_level: Level,
    /// 操作日志参数
    pub operation_log: Option<OperationLog>,
    /// 接口需要的用户权限
    pub require_permission: Option<String>,
    /// 接口参数是否包含敏感信息
    pub contains_sensitive_param: bool,
    /// 接口限流配置
    pub throttles: Vec<ThrottleConfig>,
    /// 接口扩展
    pub extensions: IndexMap<String, Arc<dyn Any + Send + Sync>>,
    /// 接口文档扩展
    pub openapi_extensions: IndexMap<String, DynamicValue>,
    /// 接口文档请求header
    pub openapi_request_headers: IndexMap<String, (String, bool)>,
    /// 接口文档响应header
    pub openapi_response_headers: IndexMap<String, (String, bool)>,
}

impl Default for RouteBaseConfig {
    fn default() -> Self {
        Self {
            api_group: Default::default(),
            path: "".to_string(),
            method: Default::default(),
            handler_name: "".to_string(),
            request_parameter: None,
            request_body: None,
            response_body: None,
            tags: vec![],
            summary: "".to_string(),
            description: vec![],
            show_doc: true,
            order: None,
            author: vec![],
            validate_group: None,
            show_security: false,
            enable_default_prefix: false,
            enable_token: false,
            enable_auto_transaction: true,
            enable_log_param: None,
            log_param_level: Level::DEBUG,
            operation_log: None,
            require_permission: None,
            contains_sensitive_param: false,
            throttles: vec![],
            extensions: Default::default(),
            openapi_extensions: Default::default(),
            openapi_request_headers: Default::default(),
            openapi_response_headers: Default::default(),
        }
    }
}

impl RouteBaseConfig {
    /// 获取Route路径
    pub fn get_route_path(application: &Application, config: &RouteBaseConfig) -> String {
        let mut path = if config.enable_default_prefix {
            format!("{}{}", application.get_server_config().expect("No Server Config found").default_api_prefix, config.path)
        } else {
            config.path.to_string()
        };
        while path.contains("//") {
            path = path.replace("//", "/")
        }
        path
    }
    /// 是否需要生成代理Handler
    pub(crate) fn should_delegate_handler(&self) -> bool {
        if self.throttles.not_empty() {
            return true;
        }
        false
    }
}

/// Http Method
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
pub enum HttpMethod {
    /// Options
    OPTIONS,
    /// Get
    GET,
    /// Post
    POST,
    /// Put
    PUT,
    /// Delete
    DELETE,
    /// Head
    HEAD,
    /// Trace
    TRACE,
    /// Connect
    CONNECT,
    /// Patch
    PATCH,
}

impl FromStr for HttpMethod {
    type Err = AppError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from(s)
    }
}

impl HttpMethod {
    /// 从Method构建
    pub fn from_method(method: Method) -> Self {
        match method {
            Method::OPTIONS => Self::OPTIONS,
            Method::GET => Self::GET,
            Method::POST => Self::POST,
            Method::PUT => Self::PUT,
            Method::DELETE => Self::DELETE,
            Method::HEAD => Self::HEAD,
            Method::TRACE => Self::TRACE,
            Method::CONNECT => Self::CONNECT,
            Method::PATCH => Self::PATCH,
            _ => panic!("unsupported method: {}", method),
        }
    }

    /// 转换为Method
    pub fn to_method(&self) -> Method {
        match self {
            HttpMethod::OPTIONS => Method::OPTIONS,
            HttpMethod::GET => Method::GET,
            HttpMethod::POST => Method::POST,
            HttpMethod::PUT => Method::PUT,
            HttpMethod::DELETE => Method::DELETE,
            HttpMethod::HEAD => Method::HEAD,
            HttpMethod::TRACE => Method::TRACE,
            HttpMethod::CONNECT => Method::CONNECT,
            HttpMethod::PATCH => Method::PATCH,
        }
    }
}

impl Display for HttpMethod {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            HttpMethod::OPTIONS => "OPTIONS",
            HttpMethod::GET => "GET",
            HttpMethod::POST => "POST",
            HttpMethod::PUT => "PUT",
            HttpMethod::DELETE => "DELETE",
            HttpMethod::HEAD => "HEAD",
            HttpMethod::TRACE => "TRACE",
            HttpMethod::CONNECT => "CONNECT",
            HttpMethod::PATCH => "PATCH",
        };
        f.write_str(s)
    }
}

impl Default for HttpMethod {
    fn default() -> Self {
        Self::GET
    }
}

impl TryFrom<&str> for HttpMethod {
    type Error = AppError;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        from_str(value)
    }
}

impl TryFrom<String> for HttpMethod {
    type Error = AppError;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        from_str(value.as_str())
    }
}

impl TryFrom<&String> for HttpMethod {
    type Error = AppError;

    fn try_from(value: &String) -> Result<Self, Self::Error> {
        from_str(value.as_str())
    }
}

impl TryFrom<&mut String> for HttpMethod {
    type Error = AppError;

    fn try_from(value: &mut String) -> Result<Self, Self::Error> {
        from_str(value.as_str())
    }
}

fn from_str(value: &str) -> AppResult<HttpMethod> {
    match value {
        "OPTIONS" => Ok(HttpMethod::OPTIONS),
        "GET" => Ok(HttpMethod::GET),
        "POST" => Ok(HttpMethod::POST),
        "PUT" => Ok(HttpMethod::PUT),
        "DELETE" => Ok(HttpMethod::DELETE),
        "HEAD" => Ok(HttpMethod::HEAD),
        "TRACE" => Ok(HttpMethod::TRACE),
        "CONNECT" => Ok(HttpMethod::CONNECT),
        "PATCH" => Ok(HttpMethod::PATCH),
        _ => Err(app_system_error!("unkown http method string: {}", value)),
    }
}

type GlobalRoutes = Arc<RwLock<Vec<Box<dyn Fn() -> Vec<RouteConfig> + Send + Sync + 'static>>>>;
static GLOBAL_ROUTES: Lazy<GlobalRoutes> = Lazy::new(|| Arc::new(RwLock::new(Vec::new())));

/// Route注册器
pub struct RouteRegister;

impl RouteRegister {
    /// 注册全局Route函数
    pub fn regist_route<F: Fn() -> RouteConfig + Send + Sync + 'static>(f: F) {
        let mut lock = GLOBAL_ROUTES.write().expect("GLOBAL_ROUTES write lock failed.");
        lock.push(Box::new(move || vec![f()]));
    }
    /// 注册全局Route函数
    pub fn regist_routes<F: Fn() -> Vec<RouteConfig> + Send + Sync + 'static>(f: F) {
        let mut lock = GLOBAL_ROUTES.write().expect("GLOBAL_ROUTES write lock failed.");
        lock.push(Box::new(f));
    }

    /// 获取全局注册的Route数目
    pub fn get_registed_routes_count() -> usize {
        let lock = GLOBAL_ROUTES.read().expect("GLOBAL_ROUTES read lock failed.");
        lock.iter().map(|f| f().len()).sum()
    }

    /// 获取全局注册的Route
    pub fn get_registed_routes() -> Vec<RouteConfig> {
        let lock = GLOBAL_ROUTES.read().expect("GLOBAL_ROUTES read lock failed.");
        let mut routes = Vec::with_capacity(lock.len());
        for f in lock.iter() {
            let mut route = f();
            routes.append(&mut route);
        }
        routes
    }

    /// 获取全局注册的Route
    pub fn get_registed_routes_config() -> Vec<RouteBaseConfig> {
        let lock = GLOBAL_ROUTES.read().expect("GLOBAL_ROUTES read lock failed.");
        let mut routes = Vec::with_capacity(lock.len());
        for f in lock.iter() {
            let mut route = f().into_iter().map(|v| v.config).collect::<Vec<RouteBaseConfig>>();
            routes.append(&mut route);
        }
        routes
    }
}

/// Route构造器
pub struct RouteBuilder {
    api_group: IndexSet<String>,
    path: String,
    method: Method,
    pub(crate) handler_name: String,
    pub(crate) request_parameter: Option<Vec<Parameter>>,
    pub(crate) request_body: Option<RequestBody>,
    pub(crate) response_body: Option<Responses>,
    tags: Vec<String>,
    summary: String,
    description: Vec<String>,
    show_doc: bool,
    order: Option<i32>,
    author: Vec<String>,
    validate_group: Option<Vec<&'static str>>,
    show_security: bool,
    enable_default_prefix: bool,
    enable_token: bool,
    enable_auto_transaction: bool,
    enable_log_param: Option<bool>,
    log_param_level: Level,
    operation_log: Option<OperationLog>,
    require_permission: Option<String>,
    contains_sensitive_param: bool,
    throttles: Vec<ThrottleConfig>,
    extensions: IndexMap<String, Arc<dyn Any + Send + Sync>>,
    openapi_extensions: IndexMap<String, DynamicValue>,
    openapi_request_headers: IndexMap<String, (String, bool)>,
    openapi_response_headers: IndexMap<String, (String, bool)>,
}

impl RouteBuilder {
    /// 初始化一个RouteBuilder
    pub fn new(method: Method, path: &str) -> RouteBuilder {
        RouteBuilder {
            api_group: IndexSet::new(),
            path: path.to_owned(),
            method,
            handler_name: "".to_string(),
            request_parameter: None,
            request_body: None,
            response_body: None,
            tags: vec![],
            summary: "".to_owned(),
            description: vec![],
            show_doc: false,
            order: None,
            author: vec![],
            validate_group: None,
            show_security: true,
            enable_default_prefix: true,
            enable_token: true,
            enable_auto_transaction: true,
            enable_log_param: None,
            log_param_level: Level::DEBUG,
            operation_log: None,
            require_permission: None,
            contains_sensitive_param: false,
            throttles: vec![],
            extensions: Default::default(),
            openapi_extensions: Default::default(),
            openapi_request_headers: Default::default(),
            openapi_response_headers: Default::default(),
        }
    }

    /// 以Get方式初始化
    pub fn get(path: &str) -> RouteBuilder {
        RouteBuilder::new(Method::GET, path)
    }

    /// 以Post方式初始化
    pub fn post(path: &str) -> RouteBuilder {
        RouteBuilder::new(Method::POST, path)
    }

    /// 以Put方式初始化
    pub fn put(path: &str) -> RouteBuilder {
        RouteBuilder::new(Method::PUT, path)
    }

    /// 以Patch方式初始化
    pub fn patch(path: &str) -> RouteBuilder {
        RouteBuilder::new(Method::PATCH, path)
    }

    /// 以Delete方式初始化
    pub fn delete(path: &str) -> RouteBuilder {
        RouteBuilder::new(Method::DELETE, path)
    }

    /// 设置OpenAPI所在的组
    pub fn api_group(&mut self, group: &str) -> &mut Self {
        self.api_group.insert(group.to_owned());
        self
    }

    /// 设置OpenAPI所在的组
    pub fn api_groups(&mut self, group: IndexSet<String>) -> &mut Self {
        self.api_group.extend(group.into_iter());
        self
    }

    /// 设置OpenAPI的接口标签(分组)
    pub fn tag(&mut self, tag: &str) -> &mut Self {
        self.tags.push(tag.to_owned());
        self
    }

    /// 设置OpenAPI的接口摘要(名称)
    pub fn summary(&mut self, summary: &str) -> &mut Self {
        self.summary = summary.to_owned();
        self
    }

    /// 设置OpenAPI的接口描述
    pub fn description(&mut self, description: &str) -> &mut Self {
        self.description.push(description.to_owned());
        self
    }

    /// 设置是否在OpenAPI的接口列表中显示
    pub fn show_doc(&mut self, show_doc: bool) -> &mut Self {
        self.show_doc = show_doc;
        self
    }

    /// 设置OpenAPI的接口排序
    pub fn order(&mut self, order: i32) -> &mut Self {
        self.order = Some(order);
        self
    }

    /// 设置OpenAPI的接口作者
    pub fn author(&mut self, author: &str) -> &mut Self {
        self.author.push(author.to_owned());
        self
    }

    /// 添加校验组
    pub fn validate_group(&mut self, group: &'static str) -> &mut Self {
        if self.validate_group.is_none() {
            self.validate_group = Some(Vec::new());
        }
        if let Some(validate_group) = self.validate_group.as_mut() {
            validate_group.push(group);
        }
        self
    }

    /// 设置OpenAPI的接口是否显示和Security相关的参数
    pub fn show_security(&mut self, show_security: bool) -> &mut Self {
        self.show_security = show_security;
        self
    }

    /// 是否启用接口默认前缀
    pub fn enable_default_prefix(&mut self, enable_default_prefix: bool) -> &mut Self {
        self.enable_default_prefix = enable_default_prefix;
        self
    }

    /// 是否启用用户Token
    pub fn enable_token(&mut self, enable_token: bool) -> &mut Self {
        self.enable_token = enable_token;
        self
    }

    /// 是否启用自动事务管理(POST、PUT、PATCH、DELETE接口自动附加事务)
    pub fn enable_auto_transaction(&mut self, enable_auto_transaction: bool) -> &mut Self {
        self.enable_auto_transaction = enable_auto_transaction;
        self
    }

    /// 是否启用接口请求日志
    pub fn enable_log_param(&mut self, enable_log_param: bool) -> &mut Self {
        self.enable_log_param = Some(enable_log_param);
        self
    }

    /// 设置接口请求参数日志级别
    pub fn log_param_level(&mut self, log_param_level: Level) -> &mut Self {
        self.log_param_level = log_param_level;
        self
    }

    /// 设置操作日志参数
    pub fn operation_log(&mut self, title: &str, business_type: BusinessType) -> &mut Self {
        self.operation_log = Some(
            OperationLog::new()
                .title(title)
                .business_type(business_type)
                .operator_type(OperatorType::MANAGE)
                .save_request_data(true)
                .save_response_data(true),
        );
        self
    }

    /// 设置操作日志参数
    pub fn operation_log_full(
        &mut self,
        title: &str,
        business_type: BusinessType,
        operator_type: OperatorType,
        save_request_data: bool,
        save_response_data: bool,
    ) -> &mut Self {
        self.operation_log = Some(
            OperationLog::new()
                .title(title)
                .business_type(business_type)
                .operator_type(operator_type)
                .save_request_data(save_request_data)
                .save_response_data(save_response_data),
        );
        self
    }

    /// 设置接口需要的用户权限
    pub fn require_permission(&mut self, permission: &str) -> &mut Self {
        self.require_permission = Some(permission.to_string());
        self
    }

    /// 设置接口是否包含敏感参数
    pub fn contains_sensitive_param(&mut self, contains_sensitive_param: bool) -> &mut Self {
        self.contains_sensitive_param = contains_sensitive_param;
        self
    }

    /// 设置接口限流配置
    pub fn add_throttle(&mut self, throttle_config: ThrottleConfig) -> &mut Self {
        self.throttles.push(throttle_config);
        self
    }

    /// 设置OpenAPI的请求体
    pub fn request_body<T: ApiSchema>(&mut self) -> &mut Self {
        self.request_body = T::get_request_body();
        self
    }

    /// 设置OpenAPI的请求参数
    pub fn request_parameter<T: ApiSchema>(&mut self) -> &mut Self {
        self.request_parameter = T::get_request_params();
        self
    }

    /// 设置OpenAPI的响应体
    pub fn response_body<T: ApiSchema>(&mut self) -> &mut Self {
        self.response_body = Some(T::get_responses());
        self
    }

    /// 添加接口扩展
    pub fn add_extension<T: Send + Sync + 'static>(&mut self, key: &str, value: T) -> &mut Self {
        self.extensions.insert(key.to_owned(), Arc::new(value));
        self
    }

    /// 添加OpenAPI扩展
    pub fn add_openapi_extension(&mut self, key: &str, value: DynamicValue) -> &mut Self {
        self.openapi_extensions.insert(key.to_owned(), value);
        self
    }

    /// 添加OpenAPI的请求头
    pub fn add_openapi_request_header(&mut self, name: &str, description: &str, required: bool) -> &mut Self {
        self.openapi_request_headers.insert(name.to_owned(), (description.to_owned(), required));
        self
    }

    /// 添加OpenAPI的响应头
    pub fn add_openapi_response_header(&mut self, name: &str, description: &str, required: bool) -> &mut Self {
        self.openapi_response_headers.insert(name.to_owned(), (description.to_owned(), required));
        self
    }

    /// 生成Route配置
    pub(crate) fn to_route(&self) -> RouteConfig {
        RouteConfig {
            route: None,
            config: RouteBaseConfig {
                api_group: self.api_group.clone(),
                path: self.path.clone(),
                method: HttpMethod::from_method(self.method.clone()),
                handler_name: self.handler_name.clone(),
                request_parameter: self.request_parameter.clone(),
                request_body: self.request_body.clone(),
                response_body: self.response_body.clone(),
                tags: self.tags.clone(),
                summary: self.summary.clone(),
                description: self.description.clone(),
                show_doc: self.show_doc,
                order: self.order,
                author: self.author.clone(),
                enable_token: self.enable_token,
                enable_auto_transaction: self.enable_auto_transaction,
                enable_log_param: self.enable_log_param,
                enable_default_prefix: self.enable_default_prefix,
                contains_sensitive_param: self.contains_sensitive_param,
                throttles: self.throttles.clone(),
                extensions: self.extensions.clone(),
                openapi_extensions: self.openapi_extensions.clone(),
                openapi_request_headers: self.openapi_request_headers.clone(),
                openapi_response_headers: self.openapi_response_headers.clone(),
                show_security: self.show_security,
                operation_log: self.operation_log.clone(),
                require_permission: self.require_permission.clone(),
                validate_group: self.validate_group.clone(),
                log_param_level: self.log_param_level,
            },
        }
    }
}

/// Route组
pub struct RouteGroup {
    group: IndexSet<String>,
    path: String,
    tag: String,
    author: String,
    order: i32,
}

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

impl RouteGroup {
    /// 初始化
    pub fn new() -> RouteGroup {
        RouteGroup {
            group: IndexSet::new(),
            path: "".to_string(),
            tag: "".to_string(),
            author: "".to_string(),
            order: 100,
        }
    }

    /// 设置OpenApi的Group
    pub fn group(&mut self, group: &str) -> &mut Self {
        self.group.insert(group.to_owned());
        self
    }

    /// 设置OpenApi的Group
    pub fn groups(&mut self, group: IndexSet<String>) -> &mut Self {
        self.group.extend(group.into_iter());
        self
    }

    /// 设置该Group下的Route接口path前缀
    pub fn path(&mut self, path: &str) -> &mut Self {
        self.path = path.to_owned();
        self
    }

    /// 设置该Group下Route的OpenAPI的标签
    pub fn tag(&mut self, tag: &str) -> &mut Self {
        self.tag = tag.to_owned();
        self
    }

    /// 设置该Group下Route的OpenAPI的作者
    pub fn author(&mut self, author: &str) -> &mut Self {
        self.author = author.to_owned();
        self
    }

    /// 设置该Group下Route的OpenAPI的排序
    pub fn order(&mut self, order: i32) -> &mut Self {
        self.order = order;
        self
    }

    /// 设置该Group下Route
    pub fn routes(&self, mut routes: Vec<RouteConfig>) -> Vec<RouteConfig> {
        let mut order = 0;
        for route in routes.iter_mut() {
            order += 1;
            route.config.api_group.extend(self.group.iter().cloned());
            route.config.path = self.path.to_owned() + route.config.path.as_str();
            if route.config.tags.is_empty() && !self.tag.as_str().is_empty() {
                route.config.tags.push(self.tag.to_owned());
            }
            if route.config.author.is_empty() && !self.author.as_str().is_empty() {
                route.config.author.push(self.author.to_owned());
            }
            route.config.order = match route.config.order {
                None => Some(self.order * 100 + order),
                Some(d) => Some(self.order * 100 + d),
            };
        }
        routes
    }
}