dubbo_config/
protocol.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use std::collections::HashMap;
19
20use serde::{Deserialize, Serialize};
21
22pub const DEFAULT_PROTOCOL: &str = "triple";
23
24#[derive(Default, Debug, Clone, Serialize, Deserialize)]
25pub struct Protocol {
26    pub ip: String,
27    pub port: String,
28    pub name: String,
29
30    #[serde(skip_serializing, skip_deserializing)]
31    pub params: HashMap<String, String>,
32}
33
34pub type ProtocolConfig = HashMap<String, Protocol>;
35
36pub trait ProtocolRetrieve {
37    fn get_protocol(&self, protocol_key: &str) -> Option<Protocol>;
38    fn get_protocol_or_default(&self, protocol_key: &str) -> Protocol;
39}
40
41impl Protocol {
42    pub fn name(self, name: String) -> Self {
43        Self { name, ..self }
44    }
45
46    pub fn ip(self, ip: String) -> Self {
47        Self { ip, ..self }
48    }
49
50    pub fn port(self, port: String) -> Self {
51        Self { port, ..self }
52    }
53
54    pub fn params(self, params: HashMap<String, String>) -> Self {
55        Self { params, ..self }
56    }
57
58    pub fn to_url(self) -> String {
59        format!("{}://{}:{}", self.name, self.ip, self.port)
60    }
61}
62
63impl ProtocolRetrieve for ProtocolConfig {
64    fn get_protocol(&self, protocol_key: &str) -> Option<Protocol> {
65        let result = self.get(protocol_key);
66        if let Some(..) = result {
67            Some(result.unwrap().clone())
68        } else {
69            None
70        }
71    }
72
73    fn get_protocol_or_default(&self, protocol_key: &str) -> Protocol {
74        let result = self.get_protocol(protocol_key);
75        if let Some(..) = result {
76            result.unwrap().clone()
77        } else {
78            let result = self.get_protocol(protocol_key);
79            if result.is_none() {
80                panic!("default triple protocol dose not defined.")
81            } else {
82                result.unwrap()
83            }
84        }
85    }
86}