HttpDispatcher.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET.Server
  4. {
  5. [CodeProcess]
  6. public class HttpDispatcher: Singleton<HttpDispatcher>, ISingletonAwake
  7. {
  8. private readonly Dictionary<string, Dictionary<int, IHttpHandler>> dispatcher = new();
  9. public void Awake()
  10. {
  11. HashSet<Type> types = CodeTypes.Instance.GetTypes(typeof (HttpHandlerAttribute));
  12. foreach (Type type in types)
  13. {
  14. object[] attrs = type.GetCustomAttributes(typeof(HttpHandlerAttribute), false);
  15. if (attrs.Length == 0)
  16. {
  17. continue;
  18. }
  19. HttpHandlerAttribute httpHandlerAttribute = (HttpHandlerAttribute)attrs[0];
  20. object obj = Activator.CreateInstance(type);
  21. IHttpHandler ihttpHandler = obj as IHttpHandler;
  22. if (ihttpHandler == null)
  23. {
  24. throw new Exception($"HttpHandler handler not inherit IHttpHandler class: {obj.GetType().FullName}");
  25. }
  26. if (!this.dispatcher.TryGetValue(httpHandlerAttribute.Path, out var dict))
  27. {
  28. dict = new Dictionary<int, IHttpHandler>();
  29. this.dispatcher.Add(httpHandlerAttribute.Path, dict);
  30. }
  31. dict.Add(httpHandlerAttribute.SceneType, ihttpHandler);
  32. }
  33. }
  34. public IHttpHandler Get(int sceneType, string path)
  35. {
  36. return this.dispatcher[path][sceneType];
  37. }
  38. }
  39. }