Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // File: Core.cs
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Net;
- using System.Text;
- using static ServiceHandler.Json;
- namespace ServiceHandler
- {
- public class ServiceHandler
- {
- readonly HttpListener listener = new HttpListener();
- readonly List<Callback> callbacks = new List<Callback>();
- public LogLevelEnum LogLevel { get; set; }
- public int Port { get; protected set; }
- public ServiceHandler(int port)
- {
- Port = port;
- }
- public ServiceHandler(int port, LogLevelEnum logLevel)
- {
- Port = port;
- LogLevel = logLevel;
- }
- public void Start()
- {
- listener.Start();
- if (LogLevel != LogLevelEnum.Nothing)
- Console.WriteLine($"Сервис запущен! Порт: {Port}");
- while (true)
- {
- var httpContext = listener.GetContext();
- var context = new Context() { HttpContext = httpContext };
- httpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
- httpContext.Response.AddHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
- httpContext.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type");
- Process(context);
- }
- }
- public void Get(string route, Action<Context> action)
- {
- var callback = new Callback()
- {
- CallbackHandler = this,
- CallbackAction = action,
- RequestString = route,
- CallbackMethod = "GET"
- };
- callbacks.Add(callback);
- listener.Prefixes.Add($"http://*:{Port}/{route}/");
- if (LogLevel != LogLevelEnum.Nothing)
- Console.WriteLine($"Новый маршрут: [GET] /{route}/");
- }
- public void Post(string route, Action<Context> action)
- {
- var callback = new Callback()
- {
- CallbackHandler = this,
- CallbackAction = action,
- RequestString = route,
- CallbackMethod = "POST"
- };
- callbacks.Add(callback);
- listener.Prefixes.Add($"http://*:{Port}/{route}/");
- if (LogLevel != LogLevelEnum.Nothing)
- Console.WriteLine($"Новый маршрут: [POST] /{route}/");
- }
- private string NormalazeUrl(string url)
- {
- return url.Substring(1, url.Length - 1);
- }
- protected void Process(Context context)
- {
- var httpContext = context.HttpContext;
- var route = httpContext.Request.RawUrl;
- route = NormalazeUrl(route);
- foreach (var t in callbacks)
- {
- if (t.RequestString.ToLower() == route.ToLower() &&
- t.CallbackMethod.ToLower() == httpContext.Request.HttpMethod.ToLower())
- {
- t.CallbackAction?.Invoke(context);
- if (LogLevel != LogLevelEnum.Nothing)
- Console.WriteLine($"{httpContext.Request.HttpMethod.ToUpper().PadRight(4)} /{route}/");
- return;
- }
- }
- var answer = $"Handler for [{httpContext.Request.HttpMethod.ToUpper()}] /{route}/ not found";
- context.Answer(new Message() { Status = "ERROR", Content = answer }, 400);
- if (LogLevel != LogLevelEnum.Nothing)
- Console.WriteLine(answer);
- }
- }
- public enum LogLevelEnum
- {
- Debug,
- Release,
- Nothing
- }
- public class Context
- {
- public HttpListenerContext HttpContext { get; set; }
- public string Body { get { return ReadBody(); } }
- public void Answer(Message message, int code = 200)
- {
- Answer(ToJson(message), code);
- }
- public void Answer(string data, int code = 200)
- {
- try
- {
- byte[] buffer = Encoding.UTF8.GetBytes(data);
- HttpContext.Response.ContentLength64 = buffer.Length;
- Stream output = HttpContext.Response.OutputStream;
- HttpContext.Response.StatusCode = code;
- output.Write(buffer, 0, buffer.Length);
- output.Close();
- }
- catch (Exception x) { Console.WriteLine(x.ToString()); }
- }
- private string ReadBody()
- {
- try
- {
- var stream = HttpContext.Request.InputStream;
- using StreamReader reader = new StreamReader(stream);
- return reader.ReadToEnd();
- }
- catch (Exception x) { throw new Exception($"Ошибка чтения тела запроса\nВероятно был вызван метод context.Answer() до попытки чтения\n\n{x}"); }
- }
- }
- public class Message
- {
- public string Status { get; set; }
- public string Content { get; set; }
- public Message() { Status = "OK"; }
- }
- public class Callback
- {
- public ServiceHandler CallbackHandler { get; set; }
- public string RequestString { get; set; }
- public Action<Context> CallbackAction { get; set; }
- public string CallbackMethod { get; set; }
- }
- }
- // File: Functions.cs
- using System;
- using System.Linq;
- using System.Text.Json;
- namespace ServiceHandler
- {
- public static class Functions
- {
- public static string[] GetArgs(Context context)
- {
- var splited = context.HttpContext.Request.Url.ToString().Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries);
- if (splited.Length < 2) return null;
- splited = splited[1].Split(new string[] { "&" }, StringSplitOptions.RemoveEmptyEntries);
- return splited.ToArray();
- }
- public static string GetParam(string[] args, string param, string defaultReturn = "")
- {
- if (args is null) return null;
- foreach (var t in args)
- {
- var splited = t.Split('=');
- if (splited.Length < 2) continue;
- if (splited[0].ToLower() == param.ToLower())
- {
- return splited[1];
- }
- }
- return defaultReturn;
- }
- }
- public static class Json
- {
- public static string ToJson(object obj)
- {
- return JsonSerializer.Serialize(obj);
- }
- public static T FromJson<T>(string data)
- {
- return JsonSerializer.Deserialize<T>(data);
- }
- }
- }
- // Example of using:
- var service = new ServiceHandler(1010);
- service.Get("api", (context) => {
- context.Answer("Hello!");
- });
- service.Post("api/test-body", (context) => {
- context.Answer("Hello! Body: " + context.Body);
- });
- service.Start();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement