RpcRoot.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net.Http;
  5. namespace NTMiner {
  6. public static partial class RpcRoot {
  7. public static string OfficialServerHost { get; private set; }
  8. public static int OfficialServerPort;
  9. public static string OfficialServerAddress = SetOfficialServerAddress("server.ntminer.com:3339");
  10. public static string SetOfficialServerAddress(string address) {
  11. if (!address.Contains(":")) {
  12. address = address + ":" + 3339;
  13. }
  14. OfficialServerAddress = address;
  15. string[] parts = address.Split(':');
  16. if (parts.Length != 2 || !int.TryParse(parts[1], out int port)) {
  17. throw new InvalidProgramException();
  18. }
  19. OfficialServerHost = parts[0];
  20. OfficialServerPort = port;
  21. return address;
  22. }
  23. /// <summary>
  24. /// 给定一个类型,返回基于命名约定的控制器名。如果给定的类型名不以Consoller为后缀则引发
  25. /// InvalidProgramException异常,如果给定的类型是接口类型但不以I开头同样会异常。
  26. /// </summary>
  27. /// <typeparam name="T"></typeparam>
  28. /// <returns></returns>
  29. public static string GetControllerName<T>() {
  30. Type t = typeof(T);
  31. string name = t.Name;
  32. if (t.IsGenericType) {
  33. name = name.Substring(0, name.IndexOf('`'));
  34. }
  35. if (!name.EndsWith("Controller")) {
  36. throw new InvalidProgramException("控制器类型名需要以Controller为后缀");
  37. }
  38. int startIndex = 0;
  39. int length = name.Length - "Controller".Length;
  40. if (t.IsInterface) {
  41. if (name[0] != 'I') {
  42. throw new InvalidProgramException("接口类型名需要以I为开头");
  43. }
  44. startIndex = 1;
  45. length -= 1;
  46. }
  47. return name.Substring(startIndex, length);
  48. }
  49. public static string GetUrl(string host, int port, string controller, string action, Dictionary<string, string> query) {
  50. string queryString = string.Empty;
  51. if (query != null && query.Count != 0) {
  52. queryString = "?" + string.Join("&", query.Select(a => a.Key + "=" + a.Value));
  53. }
  54. return $"http://{host}:{port.ToString()}/api/{controller}/{action}{queryString}";
  55. }
  56. public static HttpClient CreateHttpClient() {
  57. return new HttpClient {
  58. Timeout = TimeSpan.FromSeconds(20)
  59. };
  60. }
  61. public static void SetTimeout(this HttpClient client, int? timeountMilliseconds) {
  62. if (!timeountMilliseconds.HasValue || timeountMilliseconds.Value < 0) {
  63. return;
  64. }
  65. if (timeountMilliseconds != 0) {
  66. if (timeountMilliseconds < 100) {
  67. timeountMilliseconds *= 1000;
  68. }
  69. client.Timeout = TimeSpan.FromMilliseconds(timeountMilliseconds.Value);
  70. }
  71. }
  72. }
  73. }