using Serein.Library;
using Serein.Library.Api;
using Serein.Library.Utils;
using System.Net;
using System.Text;
namespace Serein.Proto.HttpApi
{
///
/// 对于 HttpListenerContext 的拓展服务
///
public class SereinWebApiService
{
private readonly PathRouter _pathRouter;
//private RequestLimiter? requestLimiter;
///
/// 初始化处理器
///
///
public SereinWebApiService(ISereinIOC sereinIOC)
{
_pathRouter = new PathRouter(sereinIOC);
}
///
/// 添加处理模块
///
///
public void AddHandleModule() where T : ControllerBase
{
_pathRouter.AddHandle(typeof(T));
}
///
/// 添加处理模块
///
///
public void AddHandleModule(Type type)
{
_pathRouter.AddHandle(type);
}
///
/// 获取路由信息
///
///
public List GetRouterInfos()
{
return _pathRouter.GetRouterInfos();
}
///
/// 传入方法调用结果,返回最终回复的内容和状态码
///
private Func? OnBeforeReplying;
///
/// 设置回复前的处理函数
///
///
public void SetOnBeforeReplying(Func func)
{
OnBeforeReplying = func;
}
///
/// 请求时的处理函数,传入API类型、URL、Body
///
///
public void SetOnBeforeRequest(Func func)
{
_pathRouter.OnBeforRequest = func;
}
///
/// 处理请求
///
///
///
public async Task HandleAsync(HttpListenerContext context)
{
// 获取远程终结点信息
var remoteEndPoint = context.Request.RemoteEndPoint;
// 获取用户的IP地址和端口
IPAddress ipAddress = remoteEndPoint.Address;
int port = remoteEndPoint.Port;
SereinEnv.WriteLine(InfoType.INFO, "外部连接:" + ipAddress.ToString() + ":" + port);
// 添加CORS头部
context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
context.Response.Headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type");
// 处理OPTIONS预检请求
if (context.Request.HttpMethod == "OPTIONS")
{
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.Close();
return;
}
/*if (requestLimiter is not null)
{
if (!requestLimiter.AllowRequest(context.Request))
{
SereinEnv.WriteLine(InfoType.INFO, "接口超时");
context.Response.StatusCode = (int)HttpStatusCode.NotFound; // 返回 404 错误
}
}*/
var invokeResult = await _pathRouter.HandleAsync(context); // 路由解析
(var result, var code) = (OnBeforeReplying is not null) switch
{
true => OnBeforeReplying.Invoke(invokeResult),
false => (invokeResult.Data, HttpStatusCode.OK),
};
var json = (result is not null) switch
{
true => JsonHelper.Serialize(result),
false => string.Empty
};
byte[] buffer = Encoding.UTF8.GetBytes(json);
var response = context.Response; // 获取响应对象
response.ContentLength64 = buffer.Length;
response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.StatusCode = (int)code; // 返回 200 成功
context.Response.Close(); // 关闭响应
}
}
///
/// 外部请求的信息
///
public class ApiRequestInfo
{
///
/// 请求编号
///
public long RequestId { get; set; }
///
/// API类型 GET/POST
///
public string ApiType { get; set; }
///
/// 请求的URL
///
public string Url { get; set; }
///
/// 请求的Body
///
public string? Body { get; set; }
}
}