< Summary

Information
Class: NanoRoute.HttpListenerRouter
Assembly: NanoRoute.dll
File(s): /home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Public/HttpListener/HttpListenerRouter.cs
Line coverage
97%
Covered lines: 40
Uncovered lines: 1
Coverable lines: 41
Total lines: 204
Line coverage: 97.5%
Branch coverage
N/A
Covered branches: 0
Total branches: 0
Branch coverage: N/A
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBlocks covered Blocks not covered
HttpListenerRouter()100
HttpListenerRouter(...)20
GetRequest(...)421
CreateBuilder()50

File(s)

/home/runner/work/nanoroute/nanoroute/Src/NanoRoute/Public/HttpListener/HttpListenerRouter.cs

#LineLine coverage
 1/********************************************************************************
 2* HttpListenerRouter.cs                                                         *
 3*                                                                               *
 4* Author: Denes Solti                                                           *
 5********************************************************************************/
 6using System;
 7using System.Collections.Frozen;
 8using System.Collections.Generic;
 9using System.Diagnostics;
 10using System.IO;
 11using System.Net;
 12using System.Net.Http;
 13using System.Net.Http.Headers;
 14using System.Threading;
 15using System.Threading.Tasks;
 16
 17namespace NanoRoute
 18{
 19    using Internals;
 20
 21    /// <summary>
 22    /// Routes <see cref="HttpListenerContext"/> instances through a NanoRoute pipeline.
 23    /// </summary>
 24    /// <remarks>
 25    /// This adapter converts incoming <see cref="HttpListener"/> traffic into the core
 26    /// <see cref="HttpRequestMessage"/>/<see cref="HttpResponseMessage"/> pipeline used by NanoRoute.
 27    /// </remarks>
 28    /// <example>
 29    /// <code>
 30    /// HttpListenerRouter router = HttpListenerRouter
 31    ///     .CreateBuilder()
 32    ///     .AddDefaultValueParsers()
 33    ///     .AddHandler("GET", "/health/", (context, _) =&gt; Results.Ok())
 34    ///     .CreateRouter();
 35    /// </code>
 36    /// </example>
 37    public sealed class HttpListenerRouter : RouterBase<HttpListenerRouterConfig>
 38    {
 39        #region Private
 40        [DebuggerBrowsable(DebuggerBrowsableState.Never)]
 141        private static readonly FrozenSet<string> s_managedResponseHeaders = new List<string>
 142        {
 143            "Content-Length",
 144            "Content-Type",
 145            "Transfer-Encoding",
 146            "Keep-Alive",
 147            "Server",
 148            "WWW-Authenticate"
 149        }.ToFrozenSet(StringComparer.OrdinalIgnoreCase);
 50
 151        private HttpListenerRouter(RouteScopeBuilder routes, HttpListenerRouterConfig config) : base(routes, config)
 152        {
 153        }
 54
 55        internal static async Task HandleResponse(HttpResponseMessage responseMessage, HttpListenerResponse response, Ca
 56        {
 57            response.StatusCode = (int) responseMessage.StatusCode;
 58
 59            CopyResponseHeaders(responseMessage.Headers, response.Headers);
 60
 61            if (responseMessage.Content is not null)
 62            {
 63                if (responseMessage.Content.Headers.ContentType is { } contentType)
 64                    response.ContentType = contentType.ToString();
 65
 66                CopyResponseHeaders(responseMessage.Content.Headers, response.Headers);
 67
 68                using Stream contentStream = await responseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false);
 69
 70                if (contentStream.CanSeek)
 71                {
 72                    long contentLength = contentStream.Length - contentStream.Position;
 73                    if (contentLength >= 0)
 74                        response.ContentLength64 = contentLength;
 75                }
 76
 77                // https://github.com/dotnet/dotnet/blob/b0f34d51fccc69fd334253924abd8d6853fad7aa/src/runtime/src/librar
 78                await contentStream.CopyToAsync(response.OutputStream, 81920, cancellation).ConfigureAwait(false);
 79            }
 80
 81            response.Close();
 82
 83            static void CopyResponseHeaders(HttpHeaders headers, WebHeaderCollection target)
 84            {
 85                foreach (KeyValuePair<string, IEnumerable<string>> header in headers)
 86                    if (!s_managedResponseHeaders.Contains(header.Key))
 87                        foreach (string value in header.Value)
 88                            target.Add(header.Key, value);
 89            }
 90        }
 91
 92        internal static HttpRequestMessage GetRequest(HttpListenerRequest request)
 193        {
 194            HttpRequestMessage requestMessage = new
 195            (
 196                HttpMethod.For(request.HttpMethod),
 197                request.Url
 198            );
 99
 1100            if (request.HasEntityBody)
 1101            {
 1102                requestMessage.Content = new StreamContent(request.InputStream);
 1103                requestMessage.Content.Headers.Clear();
 1104            }
 105
 1106            HttpHeaders
 1107                requestHeaders = requestMessage.Headers,
 1108                contentHeaders = requestMessage.Content?.Headers!;
 109
 1110            for (int i = 0; i < request.Headers.Count; i++)
 1111            {
 1112                string? headerName = request.Headers.GetKey(i);
 1113                if (headerName is null)
 0114                    continue;
 115
 1116                HttpHeaders headers = contentHeaders is not null && HttpRequestMessage.ContentHeaders.Contains(headerNam
 1117                    ? contentHeaders
 1118                    : requestHeaders;
 119
 1120                headers.TryAddWithoutValidation(headerName, request.Headers.GetValues(i));
 1121            }
 122
 1123            requestMessage.OriginalRequest = request;
 1124            requestMessage.TraceId = request.RequestTraceIdentifier.ToString("N");
 125
 1126            return requestMessage;
 1127        }
 128        #endregion
 129
 130        /// <summary>
 131        /// Creates a strongly typed builder for <see cref="HttpListenerRouter"/>.
 132        /// </summary>
 133        /// <returns>A builder that can register handlers, value parsers, and router configuration.</returns>
 134        /// <example>
 135        /// <code>
 136        /// RouterBuilder&lt;HttpListenerRouter, HttpListenerRouterConfig&gt; builder = HttpListenerRouter.CreateBuilder
 137        /// </code>
 138        /// </example>
 1139        public static RouterBuilder<HttpListenerRouter, HttpListenerRouterConfig> CreateBuilder() => new(static (routes,
 140
 141        /// <summary>
 142        /// Routes a single <see cref="HttpListener"/> request and writes the produced response.
 143        /// </summary>
 144        /// <param name="context">The listener context that supplies the request and receives the response.</param>
 145        /// <param name="services">The service provider exposed to handlers through <see cref="RequestContext.Services"/
 146        /// <param name="cancellation">A token that can cancel request processing and response streaming.</param>
 147        /// <returns>A task that completes after the router has finished writing the response.</returns>
 148        /// <exception cref="ArgumentNullException">
 149        /// Thrown when <paramref name="context"/> or <paramref name="services"/> is <see langword="null"/>.
 150        /// </exception>
 151        /// <exception cref="InvalidOperationException">Thrown when the request uses an unsupported HTTP method.</except
 152        /// <exception cref="HttpRequestException">
 153        /// Thrown when no handler matches the request path or a matched handler signals an HTTP failure that is not
 154        /// translated by middleware.
 155        /// </exception>
 156        /// <exception cref="OperationCanceledException">
 157        /// Thrown when the caller cancels <paramref name="cancellation"/>. The listener response is aborted before the
 158        /// exception is rethrown.
 159        /// </exception>
 160        /// <remarks>
 161        /// Request and content headers are copied into the intermediate <see cref="HttpRequestMessage"/>.
 162        /// The original <see cref="HttpListenerRequest"/> is available through the generated request message's
 163        /// <c>OriginalRequest</c> extension property.
 164        /// Response headers are copied back except for reserved <see cref="HttpListenerResponse"/> headers that
 165        /// must be managed by <see cref="HttpListener"/> itself. Cancellation is not translated into an HTTP error
 166        /// response by this adapter.
 167        /// </remarks>
 168        /// <example>
 169        /// <code>
 170        /// HttpListenerRouter router = HttpListenerRouter
 171        ///     .CreateBuilder()
 172        ///     .AddJsonErrorDetails()
 173        ///     .AddDefaultValueParsers()
 174        ///     .AddHandler("GET", "/hello/{name:str}/", (context, _) =&gt;
 175        ///         Task.FromResult(HttpResponseMessage.Json(new
 176        ///         {
 177        ///             message = $"Hello {context.Parameters["name"]}"
 178        ///         })))
 179        ///     .CreateRouter();
 180        ///
 181        /// await router.Route(listenerContext, services, cancellationToken);
 182        /// </code>
 183        /// </example>
 184        public async Task Route(HttpListenerContext context, IServiceProvider services, CancellationToken cancellation =
 185        {
 186            Ensure.NotNull(context);
 187            Ensure.NotNull(services);
 188
 189            using HttpRequestMessage request = GetRequest(context.Request);
 190
 191            try
 192            {
 193                using HttpResponseMessage response = await Route(request, services, cancellation).ConfigureAwait(false);
 194
 195                await HandleResponse(response, context.Response, cancellation).ConfigureAwait(false);
 196            }
 197            catch (OperationCanceledException)
 198            {
 199                context.Response.Abort();
 200                throw;
 201            }
 202        }
 203    }
 204}