1 module neton.server.NetonConfig; 2 3 import std.json; 4 import std.file; 5 import std.stdio; 6 import hunt.logging; 7 8 struct PeerConf 9 { 10 ulong id; 11 string ip; 12 ushort apiport; 13 ushort nodeport; 14 ushort rpcport; 15 } 16 17 class NetonConfig 18 { 19 __gshared NetonConfig _gconfig; 20 21 this() 22 { 23 } 24 25 void loadConf(string confPath) 26 { 27 try 28 { 29 auto data = getFileContent(confPath); 30 _jconf = parseJSON(cast(string)(data)); 31 } 32 catch (Exception e) 33 { 34 logError("catch netonconfig parase error : %s", e.msg); 35 } 36 praseConf(); 37 } 38 39 byte[] getFileContent(string filename) 40 { 41 byte[] content; 42 if (!exists(filename)) 43 return null; 44 byte[] data = new byte[4096]; 45 auto ifs = File(filename, "rb"); 46 while (!ifs.eof()) 47 { 48 content ~= ifs.rawRead(data); 49 } 50 ifs.close(); 51 return content; 52 } 53 54 static NetonConfig instance() 55 { 56 if (_gconfig is null) 57 _gconfig = new NetonConfig(); 58 return _gconfig; 59 } 60 61 void praseConf() 62 { 63 if (_jconf.type == JSONType.object) 64 { 65 if ("self" in _jconf) 66 { 67 auto self = _jconf["self"].object(); 68 _self.id = self["id"].integer(); 69 _self.apiport = cast(ushort) self["apiport"].integer(); 70 _self.nodeport = cast(ushort) self["nodeport"].integer(); 71 _self.rpcport = cast(ushort) self["rpcport"].integer(); 72 } 73 74 if ("peers" in _jconf) 75 { 76 auto peers = _jconf["peers"].array(); 77 foreach (peer; peers) 78 { 79 PeerConf pf; 80 pf.id = peer["id"].integer(); 81 pf.ip = peer["ip"].str(); 82 pf.apiport = cast(ushort) peer["apiport"].integer(); 83 pf.nodeport = cast(ushort) peer["nodeport"].integer(); 84 pf.rpcport = cast(ushort) peer["rpcport"].integer(); 85 _peersConf ~= pf; 86 } 87 } 88 } 89 90 logInfo("Self conf : ", _self, " | PeerConf : ", _peersConf); 91 } 92 93 @property PeerConf[] peersConf() 94 { 95 return _peersConf; 96 } 97 98 @property PeerConf selfConf() 99 { 100 return _self; 101 } 102 103 PeerConf getConf(ulong id) 104 { 105 foreach(conf; _peersConf) { 106 if(conf.id == id) 107 return conf; 108 } 109 return PeerConf.init; 110 } 111 private: 112 JSONValue _jconf; 113 PeerConf _self; 114 PeerConf[] _peersConf; 115 }