tesses-cms/Tesses.CMS/PathValueServer.cs

112 lines
3.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Tesses.WebServer;
namespace Tesses.CMS
{
public class PathValueServer : Server
{
public IServer Server {get;set;}
int paths;
public PathValueServer(int paths=1)
{
Server = new NotFoundServer();
this.paths=paths;
}
public PathValueServer(IServer inner,int paths=1)
{
Server = inner;
this.paths = paths;
}
public string GetValue(ServerContext ctx)
{
lock(kvps)
{
if(kvps.ContainsKey(ctx))
{
return kvps[ctx];
}
}
return "";
}
private void SetValue(ServerContext ctx,string val)
{
lock(kvps)
{
if(kvps.ContainsKey(ctx))
{
kvps[ctx] = val;
}
else
{
kvps.Add(ctx,val);
}
}
}
private void RemoveValue(ServerContext ctx)
{
lock(kvps)
{
kvps.Remove(ctx);
}
}
Dictionary<ServerContext,string> kvps=new Dictionary<ServerContext, string>();
public override async Task GetAsync(ServerContext ctx)
{
string[] path=ctx.UrlPath.Split(new char[]{'/'},System.StringSplitOptions.RemoveEmptyEntries);
SetValue(ctx,string.Join("/",path.Take(paths)));
ctx.UrlPath = $"/{string.Join("/",path.Skip(paths))}";
await Server.GetAsync(ctx);
RemoveValue(ctx);
}
public override async Task OptionsAsync(ServerContext ctx)
{
string[] path=ctx.UrlPath.Split(new char[]{'/'},System.StringSplitOptions.RemoveEmptyEntries);
SetValue(ctx,string.Join("/",path.Take(paths)));
ctx.UrlPath = $"/{string.Join("/",path.Skip(paths))}";
await Server.OptionsAsync(ctx);
RemoveValue(ctx);
}
public override async Task OtherAsync(ServerContext ctx)
{
string[] path=ctx.UrlPath.Split(new char[]{'/'},System.StringSplitOptions.RemoveEmptyEntries);
SetValue(ctx,string.Join("/",path.Take(paths)));
ctx.UrlPath = $"/{string.Join("/",path.Skip(paths))}";
await Server.OtherAsync(ctx);
RemoveValue(ctx);
}
public override async Task PostAsync(ServerContext ctx)
{
string[] path=ctx.UrlPath.Split(new char[]{'/'},System.StringSplitOptions.RemoveEmptyEntries);
SetValue(ctx,string.Join("/",path.Take(paths)));
ctx.UrlPath = $"/{string.Join("/",path.Skip(paths))}";
await Server.PostAsync(ctx);
RemoveValue(ctx);
}
public override async Task<bool> BeforeAsync(ServerContext ctx)
{
var urlPath = ctx.UrlPath;
string[] path=ctx.UrlPath.Split(new char[]{'/'},System.StringSplitOptions.RemoveEmptyEntries);
SetValue(ctx,string.Join("/",path.Take(paths)));
ctx.UrlPath = $"/{string.Join("/",path.Skip(paths))}";
var r= await Server.BeforeAsync(ctx);
ctx.UrlPath = urlPath;
return r;
}
}
}