using System;
using System.Net;
using System.IO;
namespace NetCoreServer
{
///
/// HTTP server is used to create HTTP Web server and communicate with clients using HTTP protocol. It allows to receive GET, POST, PUT, DELETE requests and send HTTP responses.
///
/// Thread-safe.
public class HttpServer : TcpServer
{
///
/// Initialize HTTP server with a given IP address and port number
///
/// IP address
/// Port number
public HttpServer(IPAddress address, int port) : base(address, port) { Cache = new FileCache(); }
///
/// Initialize HTTP server with a given IP address and port number
///
/// IP address
/// Port number
public HttpServer(string address, int port) : base(address, port) { Cache = new FileCache(); }
///
/// Initialize HTTP server with a given IP endpoint
///
/// IP endpoint
public HttpServer(IPEndPoint endpoint) : base(endpoint) { Cache = new FileCache(); }
///
/// Get the static content cache
///
public FileCache Cache { get; }
///
/// Add static content cache
///
/// Static content path
/// Cache prefix (default is "/")
/// Refresh cache timeout (default is 1 hour)
public void AddStaticContent(string path, string prefix = "/", TimeSpan? timeout = null)
{
timeout ??= TimeSpan.FromHours(1);
bool Handler(FileCache cache, string key, byte[] value, TimeSpan timespan)
{
HttpResponse header = new HttpResponse();
header.SetBegin(200);
header.SetContentType(Path.GetExtension(key));
header.SetHeader("Cache-Control", $"max-age={timespan.Seconds}");
header.SetBody(value);
return cache.Add(key, header.Cache.Data, timespan);
}
Cache.InsertPath(path, prefix, timeout.Value, Handler);
}
///
/// Remove static content cache
///
/// Static content path
public void RemoveStaticContent(string path) { Cache.RemovePath(path); }
///
/// Clear static content cache
///
public void ClearStaticContent() { Cache.Clear(); }
///
/// Watchdog the static content cache
///
public void Watchdog(DateTime utc) { Cache.Watchdog(utc); }
protected override TcpSession CreateSession() { return new HttpSession(this); }
}
}