using System;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
[module:
SuppressMessage("StyleCop.CSharp.ReadabilityRules",
"SA1101:PrefixLocalCallsWithThis",
Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")]
[module:
SuppressMessage("StyleCop.CSharp.NamingRules",
"SA1309:FieldNamesMustNotBeginWithUnderscore",
Justification = "Reviewed. Suppression is OK here, as it conflicts with internal naming rules.")]
[module:
SuppressMessage("StyleCop.CSharp.DocumentationRules",
"SA1633:FileMustHaveHeader",
Justification = "Reviewed. Suppression is OK here, as unknown copyright and company.")]
// ReSharper disable ArrangeThisQualifier
// ReSharper disable InconsistentNaming
namespace WireMock.Http
{
///
/// The tiny http server.
///
public class TinyHttpServer
{
///
/// The _http handler.
///
private readonly Action _httpHandler;
///
/// The _listener.
///
private readonly HttpListener _listener;
///
/// The cancellation token source.
///
private CancellationTokenSource _cts;
///
/// Initializes a new instance of the class.
///
///
/// The url prefix.
///
///
/// The http handler.
///
public TinyHttpServer(string urlPrefix, Action httpHandler)
{
_httpHandler = httpHandler;
// Create a listener.
_listener = new HttpListener();
_listener.Prefixes.Add(urlPrefix);
}
///
/// The start.
///
public void Start()
{
_listener.Start();
_cts = new CancellationTokenSource();
Task.Run(
async () =>
{
using (_listener)
{
while (!_cts.Token.IsCancellationRequested)
{
HttpListenerContext context = await _listener.GetContextAsync();
_httpHandler(context);
}
}
},
_cts.Token);
}
///
/// The stop.
///
public void Stop()
{
_cts.Cancel();
}
}
}